網站首頁 編程語言 正文
前言
使用spring開發時,進行配置主要有兩種方式,一是xml的方式,二是java config的方式。
spring技術自身也在不斷的發展和改變,從當前springboot的火熱程度來看,java config的應用是越來越廣泛了,在使用java config的過程當中,我們不可避免的會有各種各樣的注解打交道,其中,我們使用最多的注解應該就是@Autowired注解了。這個注解的功能就是為我們注入一個定義好的bean。
那么,這個注解除了我們常用的屬性注入方式之外還有哪些使用方式呢?它在代碼層面又是怎么實現的呢?這是本篇文章著重想討論的問題。
@Autowired注解用法
在分析這個注解的實現原理之前,我們不妨先來回顧一下@Autowired注解的用法。
將@Autowired注解應用于構造函數,如以下示例所示
@Component
public class BeanConfig{
@Autowired
private BeanConfig beanConfig;
@Autowired
private void setBeanConfig(BeanConfig beanConfig) {
this.beanConfig = beanConfig;
}
}
直接應用于字段是我們使用的最多的一種方式,但是使用構造方法注入從代碼層面卻是更加好的。除此之外,還有以下不太常見的幾種方式
@Autowired
private List<BeanConfig> beanConfigList;
@Autowired
private Set<BeanConfig> beanConfigSet;
@Autowired
private Map<String, BeanConfig> beanConfigMap;
@Autowired注解的作用到底是什么
@Autowired這個注解我們經常在使用,現在,我想問的是,它的作用到底是什么呢?
首先,我們從所屬范圍來看,事實上這個注解是屬于spring的容器配置的一個注解,與它同屬容器配置的注解還有:@Required,@Primary, @Qualifier等等。因此@Autowired注解是一個用于容器(container)配置的注解。
其次,我們可以直接從字面意思來看,@autowired注解來源于英文單詞autowire,這個單詞的意思是自動裝配的意思。自動裝配又是什么意思?這個詞語本來的意思是指的一些工業上的用機器代替人口,自動將一些需要完成的組裝任務,或者別的一些任務完成。而在spring的世界當中,自動裝配指的就是使用將Spring容器中的bean自動的和我們需要這個bean的類組裝在一起。
因此,筆者個人對這個注解的作用下的定義就是:將Spring容器中的bean自動的和我們需要這個bean的類組裝在一起協同使用。
接下來,我們就來看一下這個注解背后到底做了些什么工作。
@Autowired注解是如何實現的
事實上,要回答這個問題必須先弄明白的是java是如何支持注解這樣一個功能的。
java的注解實現的核心技術是反射,讓我們通過一些例子以及自己實現一個注解來理解它工作的原理。
利用反射,我們利用反射拿到這樣目標之后,得為他實現一個邏輯,這個邏輯是這些方法本身邏輯之外的邏輯,這又讓我們想起了代理,aop等知識,我們相當于就是在為這些方法做一個增強。事實上的實現主借的邏輯也大概就是這個思路。梳理一下大致步驟如下(重要):
- 利用反射機制獲取一個類的Class對象
- 通過這個class對象可以去獲取他的每一個方法method,或字段Field等等
- Method,Field等類提供了類似于getAnnotation的方法來獲取這個一個字段的所有注解
- 拿到注解之后,我們可以判斷這個注解是否是我們要實現的注解,如果是則實現注解邏輯
現在我們來實現一下這個邏輯,代碼如下:
public void postProcessProperties() throws Exception {
// 1. 獲取一個類的Class對象
Class<BeanConfig> beanConfigClass = BeanConfig.class;
// 2. 通過Class new newInstance() 實例化對象(Spring則從bean容器獲取)
BeanConfig instance = beanConfigClass.newInstance();
// 3. 獲取Class對象所有的字段
Field[] fields = beanConfigClass.getDeclaredFields();
for (Field field : fields) {
// 4. getAnnotation,判斷是否有Autowired
Autowired autowired = field.getDeclaredAnnotation(Autowired.class);
if (autowired != null) {
String fileName = field.getName();
Class<?> declaringClass = field.getDeclaringClass();
// byType或者byName從bean工廠獲取bean對象
Object bean = new Object();
// 依賴注入
field.setAccessible(true);
field.set(bean, instance);
}
}
}
從上面的實現邏輯我們不難發現,借助于java的反射我們可以直接拿到一個類里所有的方法,然后再拿到方法上的注解,當然,我們也可以拿到字段上的注解。借助于反射我們可以拿到幾乎任何屬于一個類的東西。
一個簡單的注解我們就實現完了。現在我們再回過頭來,看一下@Autowired注解是如何實現的。
知道了上面的知識,我們不難想到,上面的注解雖然簡單,但是@Autowired和他最大的區別應該僅僅在于注解的實現邏輯,其他利用反射獲取注解等等步驟應該都是一致的。先來看一下@Autowired這個注解在spring的源代碼里的定義是怎樣的,如下所示:
package org.springframework.beans.factory.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
boolean required() default true;
}
閱讀代碼我們可以看到,Autowired注解可以應用在構造方法,普通方法,參數,字段,以及注解這五種類型的地方,它的保留策略是在運行時。下面,我們不多說直接來看spring對這個注解進行的邏輯實現.
在Spring源代碼當中,Autowired注解位于包org.springframework.beans.factory.annotation之中,該包的內容如下:
經過分析,不難發現Spring對autowire注解的實現邏輯位于類:AutowiredAnnotationBeanPostProcessor之中,已在上圖標紅。其中的核心處理代碼如下:
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<>();
Class<?> targetClass = clazz;//需要處理的目標類
do {
final LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<>();
/*通過反射獲取該類所有的字段,并遍歷每一個字段,
并通過方法findAutowiredAnnotation遍歷每一個字段的所用注解
并如果用autowired修飾了,則返回auotowired相關屬性*/
ReflectionUtils.doWithLocalFields(targetClass, field -> {
AnnotationAttributes ann = findAutowiredAnnotation(field);
if (ann != null) {//校驗autowired注解是否用在了static方法上
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static fields: " + field);
}
return;
}//判斷是否指定了required
boolean required = determineRequiredStatus(ann);
currElements.add(new AutowiredFieldElement(field, required));
}
});
//和上面一樣的邏輯,但是是通過反射處理類的method
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static methods: " + method);
}
return;
}
if (method.getParameterCount() == 0) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation should only be used on methods with parameters: " +
method);
}
}
boolean required = determineRequiredStatus(ann);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new AutowiredMethodElement(method, required, pd));
}
});
//用@Autowired修飾的注解可能不止一個,因此都加在currElements這個容器里面,一起處理
elements.addAll(0, currElements);
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
return new InjectionMetadata(clazz, elements);
}
博主在源代碼里加了注釋,結合注釋就能看懂它做的事情了,最后這個方法返回的就是包含所有帶有autowire注解修飾的一個InjectionMetadata集合。這個類由兩部分組成:
public InjectionMetadata(Class<?> targetClass, Collection<InjectedElement> elements) {
this.targetClass = targetClass;
this.injectedElements = elements;
}
一是我們處理的目標類,二就是上述方法獲取到的所以elements集合。
有了目標類,與所有需要注入的元素集合之后,我們就可以實現autowired的依賴注入邏輯了,實現的方法如下:
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
它調用的方法是InjectionMetadata中定義的inject方法,如下
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Collection<InjectedElement> checkedElements = this.checkedElements;
Collection<InjectedElement> elementsToIterate =
(checkedElements != null ? checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
for (InjectedElement element : elementsToIterate) {
if (logger.isTraceEnabled()) {
logger.trace("Processing injected element of bean '" + beanName + "': " + element);
}
element.inject(target, beanName, pvs);
}
}
}
```
其邏輯就是遍歷,然后調用inject方法,inject方法其實現邏輯如下:
```java
/**
* Either this or {@link #getResourceToInject} needs to be overridden.
*/
protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
throws Throwable {
if (this.isField) {
Field field = (Field) this.member;
ReflectionUtils.makeAccessible(field);
field.set(target, getResourceToInject(target, requestingBeanName));
}
else {
if (checkPropertySkipping(pvs)) {
return;
}
try {
Method method = (Method) this.member;
ReflectionUtils.makeAccessible(method);
method.invoke(target, getResourceToInject(target, requestingBeanName));
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
對于方法的話,本質就是去調用這個方法,因此這里調用的是method.invoke.
getResourceToInject方法的參數就是要注入的bean的名字,這個方法的功能就是根據這個bean的名字去拿到它。
以上,就是@Autowire注解實現邏輯的全部分析。結合源代碼再看一遍的話,會更加清楚一點。下面是spring容器如何實現@AutoWired自動注入的過程的圖:
總結起來一句話:使用@Autowired注入的bean對于目標類來說,從代碼結構上來講也就是一個普通的成員變量,@Autowired和spring一起工作,通過反射為這個成員變量賦值,也就是將其賦為期望的類實例。
原文鏈接:https://blog.csdn.net/One_hundred_nice/article/details/125687872
相關推薦
- 2022-02-02 element ui el-dialog 居中,并且內容多的時候內部可以滾動
- 2022-09-12 Python中.py程序在CMD控制臺以指定虛擬環境運行_python
- 2022-04-19 一起來了解c語言的str函數_C 語言
- 2023-12-13 SpringMVC——訪問action報404錯誤詳解
- 2022-12-23 C++中類的構造函數初始值列表解讀_C 語言
- 2021-12-10 antd react hooks From表單格式模板
- 2023-02-06 C#實現將聊天數據發送加密_C#教程
- 2022-05-05 Entity?Framework表拆分為多個實體_實用技巧
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支