Spring?Boot?@Autowired?@Resource屬性賦值時機探究
@Resource
先貼出測試類
@Service public class TransactionServiceTest { @Resource private IQrcodeAdScheduleService qrcodeAdScheduleService; }
Spring Boot啟動之后調(diào)用棧信息
圖1
圖2
由圖1,圖2可知InjectionMetadata.inject()執(zhí)行屬性織入邏輯,下面是部分細節(jié)
protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs) throws Throwable { if (this.isField) { Field field = (Field) this.member; ReflectionUtils.makeAccessible(field); //通過反射對目標target對象也就是我們之前定義的TransactionServiceTest的屬性賦值 field.set(target, getResourceToInject(target, requestingBeanName)); } }
其中,CommonAnnotationBeanPostProcessor.ResourceElement的member屬性存儲的是Filed信息,對于本示例就是:
圖3
@Autowired
對于@Autowired來說,就是AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement.inject():
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { Field field = (Field) this.member; Object value; if (this.cached) { value = resolvedCachedArgument(beanName, this.cachedFieldValue); } else { DependencyDescriptor desc = new DependencyDescriptor(field, this.required); desc.setContainingClass(bean.getClass()); Set<String> autowiredBeanNames = new LinkedHashSet<>(1); Assert.state(beanFactory != null, "No BeanFactory available"); TypeConverter typeConverter = beanFactory.getTypeConverter(); try { //遞歸調(diào)用createBean()實例化目標bean的屬性bean實例 value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter); } catch (BeansException ex) { throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex); } synchronized (this) { if (!this.cached) { if (value != null || this.required) { this.cachedFieldValue = desc; registerDependentBeans(beanName, autowiredBeanNames); if (autowiredBeanNames.size() == 1) { String autowiredBeanName = autowiredBeanNames.iterator().next(); if (beanFactory.containsBean(autowiredBeanName) && beanFactory.isTypeMatch(autowiredBeanName, field.getType())) { this.cachedFieldValue = new ShortcutDependencyDescriptor( desc, autowiredBeanName, field.getType()); } } } else { this.cachedFieldValue = null; } this.cached = true; } } } if (value != null) { //通過field進行賦值 ReflectionUtils.makeAccessible(field); field.set(bean, value); } } }
其他的流程一毛一樣啊~
以上就是Spring Boot @Autowired @Resource屬性賦值時機探究的詳細內(nèi)容,更多關于SpringBoot @Autowired @Resource的資料請關注腳本之家其它相關文章!
相關文章
Java抽象類、繼承及多態(tài)和適配器的實現(xiàn)代碼
這篇文章主要介紹了Java抽象類、繼承及多態(tài)和適配器的實現(xiàn),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-06-06Java中避免NullPointerException的方法總結(jié)
這篇文章主要介紹了Java中避免NullPointerException的方法總結(jié)的相關資料,需要的朋友可以參考下2017-07-07java工具類之實現(xiàn)java獲取文件行數(shù)
這篇文章主要介紹了一個java工具類,可以取得當前項目中所有java文件總行數(shù),代碼行數(shù),注釋行數(shù),空白行數(shù),需要的朋友可以參考下2014-03-03基于JWT的spring boot權(quán)限驗證技術實現(xiàn)教程
這篇文章主要給大家介紹了關于基于JWT的spring boot權(quán)限驗證技術實現(xiàn)的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11