spring @EnableAspectJAutoProxy @Aspect的使用和源码流程
测试代码
@Service
public class A {
public A() {
System.out.println("A()");
}
public void say(){
System.out.println("say A");
}
}
@Aspect, say方法前打印
@Aspect
@Service
public class LogAspect {
@Before("execution(public * com.aop.dependency..*.say(..))")
public void before() {
System.out.println("... before say...");
}
}
@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.
*/
@Override
public 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 names
List<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"的代理对象的由来
简单一句话就是,AnnotationAwareAspectJAutoProxyCreator这个BeanPostProcessor集合内部缓存的@Aspect bean, 应用到raw bean, 创建代理类而来。
具体怎么创建代理的,则要阅读org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy
方法,需要先回忆下Java动态代理相关知识。
原文地址:https://blog.csdn.net/qq_26437925/article/details/145241149
免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!