1. 程式人生 > >Spring源碼解析-AutowiredAnnotationBeanPostProcessor

Spring源碼解析-AutowiredAnnotationBeanPostProcessor

face .info dep cep att 創建 info http make

1.實現了BeanPostProcessor接口,可先看這個接口 ApplicationContext可以在自動檢測BeanPostProcessor bean,在它創建完後可以創建任何的bean。

技術分享

public interface BeanPostProcessor {
    /*可以在bean實例化之前調用這個方法,類似init-method,
    *這個方法可以對bean進行操作
    */
    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;

    
/**可以在bean實例化之後調用這個方法,類似init-method, *這個方法可以對bean進行操作 */ Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException; }

簡單實現自己的一個Processor

public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws
BeansException { System.out.println("MyBeanPostProcessor before->"+beanName); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("MyBeanPostProcessor after -> "+beanName);
return bean; } }

spring-beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="student" class="org.lzyer.test.Student"></bean>
<bean class="org.lzyer.test.MyBeanPostProcessor"/>
</beans>

測試類

@Test
    public void testMyProcessor(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/spring-beans.xml");
        Student student = (Student) ctx.getBean("student");
        System.out.println(student);

    }

運行結果:

MyBeanPostProcessor before->student
MyBeanPostProcessor after -> student
org.lzyer.test.Student@4d826d77

2.AutowiredAnnotationBeanPostProcessor
BeanPostProcessor的實現類,實現了自動註入屬性、方法,可以使用jdk5的註解,默認使用spring的@Autowried和@Value註解。可以在spring配置文件中添加context:annotation-config和context:component-scan來註入AutowiredAnnotationBeanPostProcessor,另外註解的註入在xml配置文件註入之前。

3.spring在哪裏註入了BeanPostProcessor

spring容器調用refresh方法中的

// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
   /**
     * Instantiate and invoke all registered BeanPostProcessor beans,
     * respecting explicit order if given.
     * <p>Must be called before any instantiation of application beans.
     實例化並註入所有BeanPostProcessor,必須在bean實例化之前調用。
     */
    protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
    }

4.回歸到AutowiredAnnotationBeanPostProcessor
構造方法

public AutowiredAnnotationBeanPostProcessor() {
        this.autowiredAnnotationTypes.add(Autowired.class);
        this.autowiredAnnotationTypes.add(Value.class);
        try {
            this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
                    ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
            logger.info("JSR-330 ‘javax.inject.Inject‘ annotation found and supported for autowiring");
        }
        catch (ClassNotFoundException ex) {
            // JSR-330 API not available - simply skip.
        }
}

構造方法中初始化註解的類型是@Autowried,@Value以及Annotation的子類
裏面包含2個內部類AutowiredFieldElement和AutowiredMethodElement分別處理字段和方法的註解。

先看AutowiredFieldElement中inject方法

protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
            Field field = (Field) this.member;
            try {
                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<String>(1);
                    TypeConverter typeConverter = beanFactory.getTypeConverter();
                    value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
                    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)) {
                                        //對字段進行類型匹配
                                        if (beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
                                            this.cachedFieldValue = new RuntimeBeanReference(autowiredBeanName);
                                        }
                                    }
                                }
                            }
                            else {
                                this.cachedFieldValue = null;
                            }
                            this.cached = true;
                        }
                    }
                }
                if (value != null) {
                    ReflectionUtils.makeAccessible(field);
                    field.set(bean, value);//反射註入值
                }
            }
            catch (Throwable ex) {
                throw new BeanCreationException("Could not autowire field: " + field, ex);
            }
        }
    }

AutowiredMethodElement的inject方法

protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
            if (checkPropertySkipping(pvs)) {
                return;
            }
            Method method = (Method) this.member;
            try {
                Object[] arguments;
                if (this.cached) {//緩存方法參數
                    // Shortcut for avoiding synchronization...
                    arguments = resolveCachedArguments(beanName);
                }
                else {
                //獲取方法的所有參數
                    Class<?>[] paramTypes = method.getParameterTypes();
                    arguments = new Object[paramTypes.length];
                    DependencyDescriptor[] descriptors = new DependencyDescriptor[paramTypes.length];
                    Set<String> autowiredBeanNames = new LinkedHashSet<String>(paramTypes.length);
                    TypeConverter typeConverter = beanFactory.getTypeConverter();
                    //參數處理
                    for (int i = 0; i < arguments.length; i++) {
                        MethodParameter methodParam = new MethodParameter(method, i);
                        DependencyDescriptor desc = new DependencyDescriptor(methodParam, this.required);
                        desc.setContainingClass(bean.getClass());
                        descriptors[i] = desc;
                        Object arg = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
                        if (arg == null && !this.required) {
                            arguments = null;
                            break;
                        }
                        arguments[i] = arg;
                    }
                    synchronized (this) {
                        if (!this.cached) {
                            if (arguments != null) {
                                this.cachedMethodArguments = new Object[arguments.length];
                                for (int i = 0; i < arguments.length; i++) {
                                    this.cachedMethodArguments[i] = descriptors[i];
                                }
                                registerDependentBeans(beanName, autowiredBeanNames);
                                if (autowiredBeanNames.size() == paramTypes.length) {
                                    Iterator<String> it = autowiredBeanNames.iterator();
                                    for (int i = 0; i < paramTypes.length; i++) {
                                        String autowiredBeanName = it.next();
                                        if (beanFactory.containsBean(autowiredBeanName)) {
                                            if (beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) {
                                                this.cachedMethodArguments[i] = new RuntimeBeanReference(autowiredBeanName);
                                            }
                                        }
                                    }
                                }
                            }
                            else {
                                this.cachedMethodArguments = null;
                            }
                            this.cached = true;
                        }
                    }
                }
                if (arguments != null) {
                    ReflectionUtils.makeAccessible(method);
                    method.invoke(bean, arguments);//反射調用方法
                }
            }
            catch (InvocationTargetException ex) {
                throw ex.getTargetException();
            }
            catch (Throwable ex) {
                throw new BeanCreationException("Could not autowire method: " + method, ex);
            }
        }

查找註解

private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) {
        for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
            AnnotationAttributes ann = AnnotatedElementUtils.getAnnotationAttributes(ao, type.getName());
            if (ann != null) {
                return ann;
            }
        }
        return null;
    }

Spring源碼解析-AutowiredAnnotationBeanPostProcessor