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;
}
從源碼中,我們可以看到以下幾點:
- 該注解可以用在 構造函數、方法、方法內的參數、類屬性和注解上;
- 該注解在程序運行時有效;
- 有一個屬性 required,默認true,表示該裝配是否是必須的,若是,則找不到對象的類時拋出異常;
一般用法是:
- 先添加接口,聲明接口方法;
- 添加接口實現,並使用spring三層結構的注解添加到bean中;
- 使用時,使用注解進行自動裝配;
示例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 裝配順序:
- @Resource 若不傳參,則默認通過 name 屬性匹配 bean,找不到再按照 type 屬性匹配;
- @Resource 若傳參,則根據傳遞的 name/type 去匹配 bean;
- @Resource 若同時指定了 name 和 type,則根據兩個條件同時滿足去匹配;
@Resource 和 @Autowired 區別:
- @Autowired 默認根據 type 匹配 bean,@Resource 默認按照 name;
- @Autowired 是 spring 框架的注解,@Resource 是J2EE的注解;
4、@Inject
@Inject 注解也可以實現自動裝配的功能,它是 JSR330 中的規范
@Inject 注解可以用在構造函數、方法、屬性上
@Inject 注解根據類型自動裝配,如果要使其根據名稱自動裝配,則需要 @Named 注解的配合
示例:
@Inject //根據類型自動裝配
private Product product;
@Inject
@Named("NumOne") //指定name自動裝配
private Product product;