Spring Boot @Autowired @Resource属性赋值时机探究
作者:子瞻
这篇文章主要为大家介绍了Spring Boot @Autowired @Resource属性赋值时机,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
@Resource
先贴出测试类
@Service
public class TransactionServiceTest {
@Resource
private IQrcodeAdScheduleService qrcodeAdScheduleService;
}Spring Boot启动之后调用栈信息

图1

图2
由图1,图2可知InjectionMetadata.inject()执行属性织入逻辑,下面是部分细节
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的资料请关注脚本之家其它相关文章!
