spring笔记-Autowired注解实现

了解Autowired注解,是为了了解自定义注解的实现

1.InjectedElement

1.1 AutowiredFieldElement表示被Autowired注解标记的字段
1.2 AutowiredMethodElement表示被Autowired注解标记的方法

表示被注入的元素,其包含2个子类

InjectedElement

代码实例1:
如下代码,testBean就表示一个被注入的元素

public class AutowiredTestBean {

    @Autowired
    private TestBean testBean;

    MethodTestBean methodTestBean;

    @Autowired
    public void setMethodTestBean(MethodTestBean methodTestBean) {
        this.methodTestBean = methodTestBean;
    }

    public String getName() {
        return testBean.getName() + "_" + methodTestBean.getName();
    }
}

2.InjectionMetadata

注入的元数据,包含一个Class和InjectedElement集合,如AutowiredTestBean,Class就是AutowiredTestBean,InjectedElement集合包含一个AutowiredFieldElement和一个AutowiredMethodElement

public class InjectionMetadata {
    private final Class targetClass;

    private final Collection injectedElements;

    public InjectionMetadata(Class targetClass, Collection elements) {
        this.targetClass = targetClass;
        this.injectedElements = elements;
    }
}

3.inject

找到要注入的对象,接着就需要对InjectionMetadata中的InjectedElement集合进行对象注入了

在InjectedElement实现了一个inject方法.
AutowiredFieldElement和AutowiredMethodElement各自重写了InjectedElement的inject方法.
可以猜测一下,内部的实现肯定是涉及到beanFactory的,如下代码

protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
            Field field = (Field) this.member;
            Object value;
                DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
                desc.setContainingClass(bean.getClass());
                Set autowiredBeanNames = new LinkedHashSet<>(1);
                Assert.state(beanFactory != null, "No BeanFactory available");
                TypeConverter typeConverter = beanFactory.getTypeConverter();
                try {
                    value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
                }
                catch (BeansException ex) {
                    throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
                }
            if (value != null) {
                ReflectionUtils.makeAccessible(field);
                field.set(bean, value);
            }
        }

总结一下:

  1. 自定义一个注解
  2. 自定义一个BeanPostProcessor(AutowiredAnnotationBeanPostProcessor)检测注解
  3. 自定义InjectedElement并实现inject方法,最后返回InjectionMetadata

参考:https://www.jianshu.com/p/3119e675e921

你可能感兴趣的:(spring笔记-Autowired注解实现)