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

Bean的获取与创建流程

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

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,其依赖图如下:
《Spring 源码分析《Bean的获取与创建流程》》

发现其实现了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));
}
    原文作者:Spring Boot
    原文地址: https://blog.csdn.net/a510835147/article/details/78213812
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞