Spring 源码分析《Bean的获取与创建流程》

 2019-11-02 21:28  阅读(1247)
文章分类:Spring boot

Bean的获取与创建流程

20191102100848\_1.png

applyBeanPostProcessorsAfterInitialization方法定义:

@Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
        for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
            result = beanProcessor.postProcessAfterInitialization(result, beanName);
            if (result == null) {
                return result;
            }
        }
        return result;
    }

<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

上述配置会配置AnnotationAwareAspectJAutoProxyCreator,其依赖图如下:
20191102100848\_2.png

发现其实现了BeanPostProcessor,所以在执行applyBeanPostProcessorsAfterInitialization时会调用AnnotationAwareAspectJAutoProxyCreatorpostProcessAfterInitialization方法

只有当spring配置文件中配置了至少一个Advisor时,才会创建aop代理,例如:

<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
    <bean class="CountingBeforeAdvice" id="countingBeforeAdvice"></bean>
    <bean class="org.springframework.aop.support.DefaultPointcutAdvisor">
         <property name="advice" ref="countingBeforeAdvice"></property>
     </bean>

或者

<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
    <aop:config>
         <aop:aspect id="aspect" ref="defaultPluginFactory">
             <aop:pointcut id="point" expression="execution(* *.*(..))" />
             <aop:before method="doBefore" pointcut-ref="point" />
         </aop:aspect>
     </aop:config>

测试代码,可自由加减配置进行测试

@Test
    public void contextTest(){
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        applicationContext.start();

        UserService userService = applicationContext.getBean(UserService.class);

        System.out.println(AopUtils.isAopProxy(userService));
    }

来源:http://ddrv.cn

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> Spring 源码分析《Bean的获取与创建流程》

相关推荐