Java中的自动装配注解

1、说明

springboot 框架的亮点之一就是依赖注入和自动装配,它避免了我们在写代码时纠结类的生命周期问题

本文只记录一些注解的常用方法,并不深入说明

2、@Autowired

顾名思义,该注解的作用是自动装配,和以前的 spring 不同的地方在于,它不需要再配置xml而使用getBean() 方法获取对象,而可以直接使用注解,简单方便

@Autowired 源码如下:

@Target({ElementType.CONSTRUCTOR, 
         ElementType.METHOD, 
         ElementType.PARAMETER, 
         ElementType.FIELD, 
         ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    boolean required() default true;
}

从源码中,我们可以看到以下几点:

  1. 该注解可以用在 构造函数、方法、方法内的参数、类属性和注解上
  2. 该注解在程序运行时有效;
  3. 有一个属性 required,默认true,表示该装配是否是必须的,若是,则找不到对象的类时抛出异常;

一般用法是:

  1. 先添加接口,声明接口方法;
  2. 添加接口实现,并使用spring三层结构的注解添加到bean中;
  3. 使用时,使用注解进行自动装配;

示例1:

@Autowired
private ProductInterface productServer;

这里有个问题,如果一个接口有多个实现类,那如何选择装配那个呢?

解决方法是,使用 @Qualifier 注解

示例2:

ProductInterface 接口有两个实现类,FoodProductImpl 和 FrultProductImpl

@Autowired
@Qualifer("FoodProductImpl")
private ProductInterface productServer;

如上例,@Qualifer 注解要指定需要装配的实现类的类名,注意,不是 bean 名

3、@Resource

@Resource 是 J2EE 的注解,JSR250中的规范,其作用和 @Autowired 类似,匹配不到则报错

示例:

...
@Resource
private ProductMapper productMapper;

@Resource(type=ProductMapper.class)
private ProductMapper productMapper2;
...

@Resource 装配顺序:

  1. @Resource 若不传参,则默认通过 name 属性匹配 bean,找不到再按照 type 属性匹配;
  2. @Resource 若传参,则根据传递的 name/type 去匹配 bean;
  3. @Resource 若同时指定了 name 和 type,则根据两个条件同时满足去匹配;

@Resource@Autowired 区别:

  1. @Autowired 默认根据 type 匹配 bean,@Resource 默认按照 name;
  2. @Autowired 是 spring 框架的注解,@Resource 是J2EE的注解;

4、@Inject

@Inject 注解也可以实现自动装配的功能,它是 JSR330 中的规范

@Inject 注解可以用在构造函数、方法、属性上

@Inject 注解根据类型自动装配,如果要使其根据名称自动装配,则需要 @Named 注解的配合

示例:

@Inject	//根据类型自动装配
private Product product;
@Inject
@Named("NumOne")	//指定name自动装配
private Product product;
原文地址:https://www.cnblogs.com/sherlock-lin/p/13021034.html