目录
- 测试代码
- @EnableAspectJAutoProxy
- AspectJAutoProxyRegistrar
- AnnotationAwareAspectJAutoProxyCreator
- org.springframework.context.support.AbstractApplicationContext#registerBeanPostProcessors 实例化AnnotationAwareAspectJAutoProxyCreator
- bean "a"的代理处理
- 重点分析 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary
- 反问下Advisor怎么来的?
- @Aspect Bean的缓存
- 怎么判断bean "a" 要代理
- 总结 bean "a"的代理对象的由来
测试代码
@Service
public class A {public A() {System.out.println("A()");}public void say(){System.out.println("say A");}
}
@Aspect, say方法前打印log
@Aspect
@Service
public class LogAspect {@Before("execution(public * com.aop.dependency..*.say(..))")public void before() {System.out.println("... before say...");}}
@Configuration类
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;@EnableAspectJAutoProxy
@Configuration
@ComponentScan("com.aop.dependency")
public class ConfigOne {
}
@EnableAspectJAutoProxy
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
看到了@Import
,瞬间联想到ConfigurationClassPostProcessor
这个BeanFactoryPostProcessor
, 联想不到的可阅读:https://doctording.blog.csdn.net/article/details/144865082
AspectJAutoProxyRegistrar
class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {/*** Register, escalate, and configure the AspectJ auto proxy creator based on the value* of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing* {@code @Configuration} class.*/@Overridepublic void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);AnnotationAttributes enableAspectJAutoProxy =AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);if (enableAspectJAutoProxy != null) {if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);}if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);}}}}
构造了一个BeanDefinition,beanName为"“org.springframework.aop.config.internalAutoProxyCreator”"
对应类为:org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator
AnnotationAwareAspectJAutoProxyCreator
类图如下,可以发现是一个BeanPostProcessor
org.springframework.context.support.AbstractApplicationContext#registerBeanPostProcessors 实例化AnnotationAwareAspectJAutoProxyCreator
bean "a"的代理处理
bean创建的createBean方法中会应用所有的InstantiationAwareBeanPostProcessor,org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation
接着到bean的生命周期方法的doCreateBean方法org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
在实例化之后会先应用MergedBeanDefinitionPostProcessor: org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors
AnnotationAwareAspectJAutoProxyCreator不是MergedBeanDefinitionPostProcessor,先跳过
然后是添加lambda表达式的早期对象缓存
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
初始化后发现exposedObject是代理类了:
初始化前后会执行所有Bpp的postProcessBeforeInitialization和postProcessAfterInitialization方法(可阅读:https://doctording.blog.csdn.net/article/details/145044487)
对于AnnotationAwareAspectJAutoProxyCreator,其postProcessBeforeInitialization方法是
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessBeforeInitialization
,未做处理
postProcessAfterInitialization则有处理,是
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization
/*** Create a proxy with the configured interceptors if the bean is* identified as one to proxy by the subclass.* @see #getAdvicesAndAdvisorsForBean*/
@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {if (bean != null) {Object cacheKey = getCacheKey(bean.getClass(), beanName);if (!this.earlyProxyReferences.contains(cacheKey)) {return wrapIfNecessary(bean, beanName, cacheKey);}}return bean;
}
走到了wrapIfNecessary方法
在探究spring bean循环依赖的时候也见过,见文章:https://doctording.blog.csdn.net/article/details/145224918
重点分析 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary
首先找bean的Advisor,可以看到其中一个是我们自定义的,另外一个应该是内置的
然后即可以创建代理了
反问下Advisor怎么来的?
继续debug发现是通过内部缓存的aspect Bean来的
另外注意到AbstractAutoProxyCreator是实现了BeanAware的,其可以获取到beanFactory, 在org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper#findAdvisorBeans
中可以看到使用了beanFactory
/*** Find all eligible Advisor beans in the current bean factory,* ignoring FactoryBeans and excluding beans that are currently in creation.* @return the list of {@link org.springframework.aop.Advisor} beans* @see #isEligibleBean*/
public List<Advisor> findAdvisorBeans() {// Determine list of advisor bean names, if not cached already.String[] advisorNames = this.cachedAdvisorBeanNames;if (advisorNames == null) {// Do not initialize FactoryBeans here: We need to leave all regular beans// uninitialized to let the auto-proxy creator apply to them!advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Advisor.class, true, false);this.cachedAdvisorBeanNames = advisorNames;}if (advisorNames.length == 0) {return new ArrayList<>();}List<Advisor> advisors = new ArrayList<>();for (String name : advisorNames) {if (isEligibleBean(name)) {if (this.beanFactory.isCurrentlyInCreation(name)) {if (logger.isTraceEnabled()) {logger.trace("Skipping currently created advisor '" + name + "'");}}else {try {advisors.add(this.beanFactory.getBean(name, Advisor.class));}catch (BeanCreationException ex) {Throwable rootCause = ex.getMostSpecificCause();if (rootCause instanceof BeanCurrentlyInCreationException) {BeanCreationException bce = (BeanCreationException) rootCause;String bceBeanName = bce.getBeanName();if (bceBeanName != null && this.beanFactory.isCurrentlyInCreation(bceBeanName)) {if (logger.isTraceEnabled()) {logger.trace("Skipping advisor '" + name +"' with dependency on currently created bean: " + ex.getMessage());}// Ignore: indicates a reference back to the bean we're trying to advise.// We want to find advisors other than the currently created bean itself.continue;}}throw ex;}}}}return advisors;
}
@Aspect Bean的缓存
debug发现是在@Config的全注解类生命周期执行的时候InstantiationAwareBeanPostProcessor会应用AnnotationAwareAspectJAutoProxyCreator这个beanPostProcessor(因为AnnotationAwareAspectJAutoProxyCreator确实是一个InstantiationAwareBeanPostProcessor,查看类图可知)
在org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessBeforeInstantiation
方法中会查找所有的Advisor
@Override
protected boolean shouldSkip(Class<?> beanClass, String beanName) {// TODO: Consider optimization by caching the list of the aspect namesList<Advisor> candidateAdvisors = findCandidateAdvisors();for (Advisor advisor : candidateAdvisors) {if (advisor instanceof AspectJPointcutAdvisor &&((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) {return true;}}return super.shouldSkip(beanClass, beanName);
}
对所有bean判断是否Aspect 得到
@Aspect注解很普通,如下
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Aspect {/*** Per clause expression, defaults to singleton aspect* <p/>* Valid values are "" (singleton), "perthis(...)", etc*/public String value() default "";
}
判断Aspect Bean方法
/*** We consider something to be an AspectJ aspect suitable for use by the Spring AOP system* if it has the @Aspect annotation, and was not compiled by ajc. The reason for this latter test* is that aspects written in the code-style (AspectJ language) also have the annotation present* when compiled by ajc with the -1.5 flag, yet they cannot be consumed by Spring AOP.*/
@Override
public boolean isAspect(Class<?> clazz) {return (hasAspectAnnotation(clazz) && !compiledByAjc(clazz));
}private boolean hasAspectAnnotation(Class<?> clazz) {return (AnnotationUtils.findAnnotation(clazz, Aspect.class) != null);
}
最后缓存到org.springframework.aop.aspectj.annotation.BeanFactoryAspectJAdvisorsBuilder#aspectBeanNames
list结构中
AnnotationAwareAspectJAutoProxyCreator作为InstantiationAwareBeanPostProcessor各个bean实例化都会执行到,因为有缓存,所以@Aspect bean的缓存逻辑只会执行一次
随意当执行到bean "a"的时候,可以直接从缓存中拿到
怎么判断bean “a” 要代理
bean “a” initializeBean过程中,应用AnnotationAwareAspectJAutoProxyCreator这个bpp,判断是否要代理,从缓存中取出@Aspect的bean,然后通过org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findAdvisorsThatCanApply
方法判断,比较复杂,如下图
本例 bean “a” 的say方法被LogAspect代理了,所以最后判断出有代理
@Aspect
@Service
public class LogAspect {@Before("execution(public * com.aop.dependency..*.say(..))")public void before() {System.out.println("... before say...");}}
总结 bean "a"的代理对象的由来
简单一句话就是,AnnotationAwareAspectJAutoProxyCreator这个BeanPostProcessor集合内部缓存的@Aspect bean, 应用到raw bean, 判断是否有代理,有则创建代理类而来。
AnnotationAwareAspectJAutoProxyCreator怎么来的则是当全注解类加上@EnableAspectJAutoProxy
,会通过spring内置的ConfigurationClassPostProcessor
BeanFactoryPostProcessor添加一个AnnotationAwareAspectJAutoProxyCreator
BeanPostProcessor
具体怎么创建代理的,则要阅读org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy
方法,需要先回忆下Java动态代理相关知识。