1、 @Autowire 定义
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
boolean required() default true;
}
@Autowire 注解是由 AutowiredAnnotationBeanPostProcessor 处理器来实现的。然后我们发现 AutowiredAnnotationBeanPostProcessor 实现了 MergedBeanDefinitionPostProcessor 接口中的 postProcessMergedBeanDefinition()方法。@Autowired注解正是通过这个方法实现注入类型的预解析,将需要依赖注入的属性信息封装到InjectionMetadata类中。,InjectionMetadata类中包含了需要注入的元素(injectedElements)及元素要注入的目标类(tagetClass)。
现在我们知道了AutowiredAnnotationBeanPostProcessor时Autowire的主力,那其又是如何完成依赖注入的呢?其实在Spring容器启动的时候其会调用AbstractApplicationContext类的refresh方法,其主要靠registerBeanPostProcessors()方法完成对AutowiredAnnotationBeanPostProcessor的注册,然后在finishBeanFactoryInitialization(beanFactory)方法对非延迟初始化的单例bean进行初始化时,会执行到AbstractAutowireCapableBeanFactory类的doCreateBean方法。
在doCreateBean()方法中其会调用applyMergedBeanDefinitionPostProcessors这时就会对AutowiredAnnotationBeanPostProcessor类中这个方法完成注入元素注解的预解析
然后其最终会调用doCreateBean方法中,其中会执行populateBean方法实现对属性的注入。
populateBean()方法,会遍历InstantiationAwareBeanPostProcessor,执行实例类的postProcessPropertyValues方法。
然后最终使用反射赋值。