当前位置: 首页 > 后端技术 > Java

SpringBoot@Autowired@Resource属性赋值时机?

时间:2023-04-01 21:16:12 Java

或者先贴出测试类:@ServicepublicclassTransactionServiceTest{@ResourceprivateIQrcodeAdScheduleServiceqrcodeAdScheduleService;}SpringBoot启动后的调用栈信息如下图1和图2从图1和图2可以看出InjectionMetadata.inject()执行属性编织逻辑,这里有一些细节ReflectionUtils.makeAccessible(字段);//通过反射,给target目标对象赋值,也就是我们前面定义的TransactionServiceTest的属性。field.set(target,getResourceToInject(target,requestingBeanName));其中,CommonAnnotationBeanPostProcessor.ResourceElement的成员属性存储了Filed信息。对于这个例子是:图3为@AutowiredisAutowiredAnnotationBeanPostProcessor.AutowiredFieldElement.inject():protectedvoidinject(Objectbean,@NullableStringbeanName,@NullablePropertyValuespvs)throwsThrowable{Fieldfield=(Field)t他的成员;对象值;如果(this.cached){value=resolvedCachedArgument(beanName,this.cachedFieldValue);}else{DependencyDescriptordesc=newDependencyDescriptor(field,this.required);desc.setContainingClass(bean.getClass());SetautowiredBeanNames=newLinkedHashSet<>(1);Assert.state(beanFactory!=null,"没有可用的BeanFactory");TypeConvertertypeConverter=beanFactory.getTypeConverter();try{//递归调用createBean()实例化目标bean的属性bean实例value=beanFactory.resolveDependency(desc,beanName,autowiredBeanNames,typeConverter);}catch(BeansExceptionex){thrownewUnsatisfiedDependencyException(null,beanName,newInjectionPoint(field),ex);}synchronized(this){if(!this.cached){if(value!=null||this.required){this.cachedFieldValue=desc;registerDependentBeans(beanName,autowiredBeanNames);if(autowiredBeanNames.size()==1){字符串autowiredBeanName=autowiredBeanNames.iterator().next();if(beanFactory.containsBean(autowiredBeanName)&&beanFactory.isTypeMatch(autowiredBeanName,field.getType())){this.cachedFieldValue=newShortcutDependencyDescriptor(desc,autowiredBeanName,field.getType());}}}else{this.cachedFieldValue=无效的;}this.cached=true;}}}if(value!=null){//通过字段赋值ReflectionUtils.makeAccessible(field);field.set(bean,值);一样的~嗯,总结留给各位看官吧~(太困了,该休息了)