构造器注入比setter注入要求更严格它强调我们在创建对象时必须注入某些参数而setter注入没有强制
第一步:创建javaweb项目
第二步:导入必要的IOC包,这儿有五个
“commons-logging.jar”
“spring-beans-3.2.8.RELEASE.jar”
“spring-context-3.2.8.RELEASE.jar”
“spring-core-3.2.8.RELEASE.jar”
“spring-expression-3.2.8.RELEASE.jar”
第三步:创建bean
public class People implements Serializable {
private String name;
private int age;
public People(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
第四步:导入spring配置文件,我这儿是applicationContext.xml,并且声明bean
<bean id="people" class="com.zxy.bean.People">
<!-- 通过constructor-arg标签给bean注入参数值 -->
<constructor-arg index="0" value="张三"/>
<constructor-arg index="1" value="22"/>
</bean>
第五步:写测试代码(注意这个就需要导入Junit 4的包)
@Test
public void testPeople(){
//用容器实例化bean
String conf = "applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(conf);
//获取对象
People people = ctx.getBean("people",People.class);
System.out.println(people.getName());
System.out.println(people.getAge());
}
第六步:测试结果:
张三
22