首先在eclipse上建立maven项目,关于建立方式,网上有许多教程,这里就不在赘述
在pom.xml中添加以下依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.7.RELEASE</version>
<scope>runtime</scope>
</dependency>
version中的RELEASE需要带上,不然会报错(版本名称不完整)
项目结构如下:
firstbean:
package com.springdemo;
public class firstbean {
private String something;
public String getSomething() {
return something;
}
public void setSomething(String something) {
this.something = something;
}
}
secondBean:
package com.springdemo;
public class secondBean {
private String something;
public String getSomething() {
return something;
}
public void setSomething(String something) {
this.something=something;
}
}
thirdbean:
package com.springdemo;
public class thirdbean {
private firstbean first;
private secondBean second;
private int index;
private String type;
public firstbean getFirst() {
return first;
}
public void setFirst(firstbean first) {
this.first = first;
}
public secondBean getSecond() {
return second;
}
public void setSecond(secondBean second) {
this.second = second;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
App:
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("springdemo.xml");
firstbean demo=(firstbean)context.getBean("firstbean");
demo.setSomething("I'm firstbean");
secondBean demo2=(secondBean)context.getBean("secondbean","com.springdemo.secondBean");
demo2.setSomething("I'm secondbean");
thirdbean demo3=(thirdbean)context.getBean("thirdbean","com.springdemo.thirdbean");
System.out.println(demo3.getFirst().getSomething());
System.out.println(demo3.getSecond().getSomething());
System.out.println(demo3.getIndex());
System.out.println(demo3.getType());
}
}
springdemo.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="firstbean" class="com.springdemo.firstbean"/>
<bean id="secondbean" class="com.springdemo.secondBean"/>
<bean id="thirdbean" class="com.springdemo.thirdbean">
<property name="first" ref="firstbean"/>
<property name="second" ref="secondbean"/>
<property name="index" value="1"/>
<property name="type" value="type"/>
</bean>
</beans>
执行结果:
遇到的异常:
parsing XML document from class path resource [springdemo.xml]
原因是xml文件应该放在src目录下,否则需要指明xml'文件的路径
通过上面这个例子,可以看出默认情况下spring的bean的scope为singleton