第一步:创建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”
第三步:导入spring配置文件,我这儿是applicationContext.xml,
<!-- 开启IOC组件扫描 -->
<context:component-scan
base-package="com.zxy"/>
第四步:创建并且声明bean
@Component("computer")
public class Computer implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
}
创建Programmer类,并使用@Component注解将其声明到容器中,然后使用@Resource注解在构造器上将Computer注入进来,代码如下:
setter方式注入bean
@Component
public class Teacher implements Serializable{
private Computer computer;
public Computer getComputer() {
return computer;
}
@Resource(name="computer")
public void setComputer(Computer computer) {
this.computer = computer;
System.out.println("给Teacher类注入");
}
}
属性加注解注入bean
@Component
public class Student {
@Resource()
private Computer computer;
public Computer getComputer() {
return computer;
}
public void setComputer(Computer computer) {
this.computer = computer;
}
}
第五步:写测试代码(注意这个就需要导入Junit 4的包)对应的测试代码
setter注入测试
@Test
public void TeacherTest(){
String conf = "applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(conf);
Teacher teacher = ctx.getBean("teacher",Teacher.class);
System.out.println(teacher);
System.out.println(teacher.getComputer());
}
属性注入:
@Test
public void StudentTest(){
String conf = "applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(conf);
Student student = ctx.getBean("student",Student.class);
System.out.println(student);
System.out.println(student.getComputer());
}
第六步:测试结果:
给Teacher类注入
com.zxy.bean.Teacher@2de12f6d
com.zxy.bean.Computer@1af0b4a3
com.zxy.bean.Student@175bc6c8
com.zxy.bean.Computer@a578073
这儿详细说明注解的意义:
@Resouce告诉Spring要给这个对象属性注入数据, 括号里面要注入的bean的ID, 如果要注入的bean是单例的,则括号里可以省略