工具包:
1、spring-framework-4.0.4.RELEASE的21个RELEASE的jar包
2、commons-logging-1.2.jar
参数:
1、MyEclipse10
2、JDK1.7.0_79
1. 新建Java Project,新建类Person和Phone,导入工具包1和2
public class Person {
private Phone phone;
// set方法
public void setPhone(Phone phone) {
this.phone = phone;
}
public void usePhone() {
phone.open();
}
}
public class Phone {
public void open() {
System.out.println("开机");
}
}
2. 配置管理Bean的方法
在src目录下新建配置文件beans.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-4.0.xsd">
<!-- 配置id为person的Bean,实现类为com.zz.app.Person(调用无参构造方法) -->
<bean id="person" class="com.zz.app.Person">
<!-- 调用setPhone(Phone phone)方法,把id为phone1的Bean作为参数 -->
<property name="phone" ref="phone1" />
</bean>
<!-- 配置id为phone1的Bean,实现类为com.zz.app.Phone -->
<bean id="phone1" class="com.zz.app.Phone" />
</beans>
测试代码:
public class BeanTest {
public static void main(String[] args) {
// 创建Spring容器
ApplicationContext ctx = new
ClassPathXmlApplicationContext("beans.xml");
// 获得id为person的Bean
Person p = ctx.getBean("person", Person.class);
p.usePhone();
}
}
编译、运行测试程序,可以看到以下输出:
十月 18, 2015 7:45:43 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@635a4247: startup date [Sun Oct 18 19:45:43 CST 2015]; root of context hierarchy
十月 18, 2015 7:45:43 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
开机
可以看出,根据beans.xml的配置,Spring已经装配了Person的phone属性。