7.使用@Resource注解注入依赖的bean。

第一步:创建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是单例的,则括号里可以省略

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值