Spring?Boot?@Autowired?@Resource屬性賦值時機探究
@Resource
先貼出測試類
@Service
public class TransactionServiceTest {
@Resource
private IQrcodeAdScheduleService qrcodeAdScheduleService;
}Spring Boot啟動之后調用棧信息

圖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 {
//遞歸調用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屬性賦值時機探究的詳細內容,更多關于SpringBoot @Autowired @Resource的資料請關注腳本之家其它相關文章!
相關文章
Java抽象類、繼承及多態(tài)和適配器的實現(xiàn)代碼
這篇文章主要介紹了Java抽象類、繼承及多態(tài)和適配器的實現(xiàn),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-06-06
Java中避免NullPointerException的方法總結
這篇文章主要介紹了Java中避免NullPointerException的方法總結的相關資料,需要的朋友可以參考下2017-07-07
基于JWT的spring boot權限驗證技術實現(xiàn)教程
這篇文章主要給大家介紹了關于基于JWT的spring boot權限驗證技術實現(xiàn)的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11

