• Bean装配之@Autowired注解


    @Required(不常用)

    @Autowired(常用)

    下面用例子解释以上内容:

    @Autowired注解的三种方式如下,第一种是直接在属性名上加注解,这样就可以不用在写set方法进行注入,这种方式与set方式作用一样;第二种是在set方法上加注解;第三种是在构造器上加注解

    测试代码如下:

     xml配置文件正常即可:

    图解:可以在当前类中,声明ApplicationContext的引用,然后可以用@Autowired进行注解,这时候可以在当前类中得到这个容器,并且可以使用这个容器了

    图解:

    数组也就是Set或List等,提供所有特定类型的bean是指:当Set中声明MovieCatalog时,当前的ApplicationContext中所有是Set泛型中声明类型的这种bean或它的子类,都可以被@Autowired注解,把这些bean的实例放到当前的集合当中。

    这里的key也就是所有bean的id,value也就是bean的对象,同时我们希望放在Map或者是Set和List的集合中,这种bean的实例是有顺序的,可以实现以上接口来实现。

     例子如下:

    interface的两个实现类:

    调用类实现:

     1 @Component
     2 public class BeanInvoker {
     3     
     4     //可以利用@Autowired注解,将两个实现类的实例同时注入list或map中
     5     //list中会被注解进来bean的实例,只有bean的对象
     6     @Autowired
     7     private List<BeanInterface> list;
     8     
     9     //map中会被注解进来bean的id和实例,bean的id就是class的类名第一个字母小写
    10     @Autowired
    11     private Map<String, BeanInterface> map;
    12     
    13     //将@Qualifier与@Autowired一起用,可以指定注入的某一个实现类的实例
    14     @Autowired
    15     @Qualifier("beanImplOne")
    16     private BeanInterface beanInterface;
    17     
    18     public void say() {
    19         if(null != list && 0 != list.size()) {
    20             System.out.println("list...");
    21             for(BeanInterface bean:list) {
    22                 System.out.println(bean.getClass().getName());
    23             }
    24         }
    25         else {
    26             System.out.println("List<BeanInterface> list is null....");
    27         }
    28         
    29         System.out.println();
    30         
    31         if(null != map && 0 != map.size()) { 
    32             System.out.println("map...");
    33             for(Map.Entry<String, BeanInterface> entry:map.entrySet()) {
    34                 System.out.println(entry.getKey() + "......" + entry.getValue().getClass().getName());
    35             }
    36         }
    37         else {
    38             System.out.println("Map<String, BeanInterface> map is null...");
    39         }
    40         
    41         System.out.println();
    42         
    43         if(null != beanInterface){
    44             System.out.println(beanInterface.getClass().getName());
    45         }
    46         else {
    47             System.out.println("beanInterface is null...");
    48         }
    49     }
    50 }
    View Code

    测试类:

    注释:当某个接口有多个实现类时,可以将@Qualifier与@Autowired一起用, 指定应该注入的对象的实例。@Qualifier中应该是要指定注入的bean的id

    打印结果如下:

     

  • 相关阅读:
    C# String.Compare 方法测试
    C#checked 与 unchecked
    C#枚举类型
    C#结构体
    C越界和溢出的区别
    python/matlab : 将txt文件中的数据读为numpy数组
    matlab程序里调用python文件
    Python
    Pycharm调试及快捷键技巧
    Pycharm远程连接服务器debug时报错
  • 原文地址:https://www.cnblogs.com/cing/p/7436656.html
Copyright © 2020-2023  润新知