ITPub博客

首页 > IT职业 > IT图书 > Spring - 自动注入及properties文件的使用

Spring - 自动注入及properties文件的使用

IT图书 作者:jenliang 时间:2021-09-09 09:11:30 0 删除 编辑

一、为Spring配置文件,添加annotation支持,以及 default-autowire属性




    

    

    
        
            
                
                
            
        
    

    

    
        
            jimmy.yang
        
    


 注: 相对原来的版本,有几个小变化:

a) 最开始的xml声明部分,添加了xmlns:context

b) default-autowired设置为byName,运行时,将通过配置文件中,bean的id/name,来实现自动注入(后面会有代码演示)

c) 添加了 ,这表明Spring允许在java类中,可以通过在field成员上,通过注解自动注入,而不再需要在配置文件中,手动指定property注入

d) 名为jimmy的bean,去掉...的注入配置

那么,问题来了,运行时,jimmy如何得到name,pet,computers这些属性的实例呢?

 

二、使用@Resource自动注入

Spring支持好几种注解自动注入,比如@Inject,@Resource,@Autowired,这里只演示@Resource这一种


package com.cnblogs.yjmyzz.domain;import javax.annotation.Resource;import java.util.List;public class Programmer {

    @Resource(name = "jimmy_name")    private String name;

    @Resource(name = "wangcai")    private Pet pet;

    @Resource(name = "computerlist")    private List computers;    public void show() {
        System.out.print("My name is " + name);
        System.out.print(", and I have " + computers.size() + " computer" + (computers.size() > 1 ? "s" : "") + ":");
        System.out.println();        for (Computer c : computers) {
            c.showInfo();
        }
        System.out.println("And I have a pet, everyday,when I go home, it will welcome me by  ");
        pet.welcomeMeToHome();

    }
}


对比原来的版本,去掉了所有的setter,整个类看上去非常清爽,@Resouce后的name=XXX,这里的XXX要跟Spring配置文件中,bean的id一致

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4565/viewspace-2800250/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-15

  • 博文量
    189
  • 访问量
    858