目录
@EnableAspectJAutoProxyz这个是什么?
AnnotationAwareAspectJAutoProxyCreator
AnnotationAwareAspectJAutoProxyCreator实现了BeanFactoryAware接口
AnnotationAwareAspectJAutoProxyCreator实现BeanPostProcessor接口
AnnotationAwareAspectJAutoProxyCreator实现了InstantiationAwareBeanPostProcessor接口
概念:
AOP
AOP(Aspect Oriented Programming),即面向切面编程。简单说就是那些与业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减少系统的重复代码,降低模块之间的耦合度,并有利于未来的可操作性和可维护性。
源码
@EnableAspectJAutoProxy
@EnableAspectJAutoProxyz这个是什么?
我们可以注意到,当我们要自己写一个切面的时候,在我们的配置类上面都会加上@EnableAspectJAutoProxy这个注解,那么这个注解是什么呢?这个注解的作用是让你自己写的切面起作用,那么他是怎么让我们的切面起作用的呢,下面来看一下这个注解如下图:
从这个注解中我们一眼就看出,他通过@Import注解引入了AspectJAutoProxyRegistrar这个类。
AspectJAutoProxyRegistrar这个类
AspectJAutoProxyRegistrar这个类是干什么的?
当我们进入到AspectJAutoProxyRegistrar这个类的时候,看到了他实现了ImportBeanDefinitionRegistrar这个类,ImportBeanDefinitionRegistrar这个有必要说一下,在我前几篇博客中提到过这个类,只要实现了ImportBeanDefinitionRegistrar,就可以往我们的容器中添加bean定义,那么他在这里的作用是什么呢?来看一下他的源码。
org.springframework.context.annotation.AspectJAutoProxyRegistrar#registerBeanDefinitions
org.springframework.aop.config.AopConfigUtils#registerAspectJAnnotationAutoProxyCreatorIfNecessary(org.springframework.beans.factory.support.BeanDefinitionRegistry)
org.springframework.aop.config.AopConfigUtils#registerAspectJAnnotationAutoProxyCreatorIfNecessary(org.springframework.beans.factory.support.BeanDefinitionRegistry, java.lang.Object)
-
@Nullable
-
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(
-
BeanDefinitionRegistry registry, @Nullable Object source) {
-
//注册一个名称叫org.springframework.aop.config.internalAutoProxyCreator 类型是AnnotationAwareAspectJAutoProxyCreator的bean定义
-
return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
-
}
AnnotationAwareAspectJAutoProxyCreator
AnnotationAwareAspectJAutoProxyCreator这个是类是干什么的呢?我们来看一下他的继承关系图
然后我们根据集成图,来看一下AnnotationAwareAspectJAutoProxyCreator干了些什么:
AnnotationAwareAspectJAutoProxyCreator实现了BeanFactoryAware接口
首先他实现了BeanFactoryAware接口,而我们看一下BeanFactoryAware源码,他到底是干什么的?
-
public
interface BeanFactoryAware extends Aware {
-
-
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
-
-
}
BeanFactoryAware很简单,就一个setBeanFactory方法,AbstractAutoProxyCreator实现了BeanFactoryAware,一定会复写这个方法,然后我们看一下AbstractAutoProxyCreator的setBeanFactory方法:
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#setBeanFactory
org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#setBeanFactory
-
@Override
-
public void setBeanFactory(BeanFactory beanFactory) {
-
super.setBeanFactory(beanFactory);
//调用父类的super.setBeanFactory(beanFactory);
-
if (!(beanFactory
instanceof ConfigurableListableBeanFactory)) {
-
throw
new IllegalArgumentException(
-
"AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory);
-
}
-
initBeanFactory((ConfigurableListableBeanFactory) beanFactory);
//初始化bean工厂
-
}
那么这个initBeanFactory()是怎么实现的呢,来看一下他的源码
org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#initBeanFactory
org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator#initBeanFactory
-
@Override
-
protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
-
super.initBeanFactory(beanFactory);
//1.调用父类的setBeanFactory
-
if (
this.aspectJAdvisorFactory ==
null) {
// 若 apsectj的Advisor(通知)工厂对象为空,我们就创建一个ReflectiveAspectJAdvisorFactory
-
this.aspectJAdvisorFactory =
new ReflectiveAspectJAdvisorFactory(beanFactory);
-
}
-
//不为空 我们就把aspectJAdvisorFactory 包装为BeanFactoryAspectJAdvisorsBuilderAdapter
-
this.aspectJAdvisorsBuilder =
-
new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory,
this.aspectJAdvisorFactory);
-
}
总结:实现BeanFactoryAware接口主要做了两件事:1.setBeanFactory 2.为aspectJAdvisorsBuilder的Advisor(通知)赋值
AnnotationAwareAspectJAutoProxyCreator实现BeanPostProcessor接口
我们先看看BeanPostProcessor这个接口的源码:
-
public
interface BeanPostProcessor {
-
-
-
@Nullable
-
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
-
return bean;
-
}
-
-
-
@Nullable
-
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
-
return bean;
-
}
这个接口有两个方法postProcessBeforeInitialization和postProcessAfterInitialization方法,但是AnnotationAwareAspectJAutoProxyCreator实现BeanPostProcessor接口主要是用它的postProcessAfterInitialization方法,我们来看一下AnnotationAwareAspectJAutoProxyCreator中的postProcessAfterInitialization方法源码
-
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
-
if (bean !=
null) {
-
Object cacheKey = getCacheKey(bean.getClass(), beanName);
-
if (
this.earlyProxyReferences.remove(cacheKey) != bean) {
-
return wrapIfNecessary(bean, beanName, cacheKey);
//包装bean 创建代理对象
-
}
-
}
-
return bean;
-
}
AnnotationAwareAspectJAutoProxyCreator实现了InstantiationAwareBeanPostProcessor接口
AnnotationAwareAspectJAutoProxyCreator实现InstantiationAwareBeanPostProcessor接口主要是用它的postProcessBeforeInstantiation方法,看一下这个方法的源码:
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessBeforeInstantiation
-
@Override
//找通知(advisor),放入缓存
-
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
-
Object cacheKey = getCacheKey(beanClass, beanName);
-
-
if (!StringUtils.hasLength(beanName) || !
this.targetSourcedBeans.contains(beanName)) {
//判断有没有处理过
-
if (
this.advisedBeans.containsKey(cacheKey)) {
-
return
null;
-
}
//是不是一些基础的bean(Advice,Pointcut,Advisor,AopInfrastructureBean)||该不该跳过
-
if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
//shouldSkip源码
-
this.advisedBeans.put(cacheKey, Boolean.FALSE);
-
return
null;
-
}
-
}
-
-
-
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
// 获取封装当前bean的TargetSource对象,如果不存在,则直接退出当前方法,
-
if (targetSource !=
null) {
// 否则从TargetSource中获取当前bean对象,并且判断是否需要将切面逻辑应用在当前bean上。
-
if (StringUtils.hasLength(beanName)) {
-
this.targetSourcedBeans.add(beanName);
-
}
-
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
-
Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
-
this.proxyTypes.put(cacheKey, proxy.getClass());
-
return proxy;
-
}
-
-
return
null;
-
}
创建代理对象
真正的创建代理对象是从BeanPostProcessor处理器的后置方法开始,看源码路径:
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary
org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean
org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findEligibleAdvisors
org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findAdvisorsThatCanApply
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy
然后我们分别来看一下他们的源码;
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization
-
@Override
//实例化之后
-
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
-
if (bean !=
null) {
-
Object cacheKey = getCacheKey(bean.getClass(), beanName);
////通过传入的class 和beanName生成缓存key
-
if (
this.earlyProxyReferences.remove(cacheKey) != bean) {
-
return wrapIfNecessary(bean, beanName, cacheKey);
//有没有必要包装
-
}
-
}
-
return bean;
-
}
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary
-
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
-
if (StringUtils.hasLength(beanName) &&
this.targetSourcedBeans.contains(beanName)) {
//有没有被代理过
-
return bean;
-
}
-
if (Boolean.FALSE.equals(
this.advisedBeans.get(cacheKey))) {
//不需要被通知的直接返回
-
return bean;
-
}
-
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
//是不是基础bean || 是否需要跳过
-
this.advisedBeans.put(cacheKey, Boolean.FALSE);
-
return bean;
-
}
-
-
// Create proxy if we have advice.
-
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName,
null);
//获取通知 源码
-
if (specificInterceptors != DO_NOT_PROXY) {
//获取的不为空
-
this.advisedBeans.put(cacheKey, Boolean.TRUE);
-
Object proxy = createProxy(
//创建代理对象 源码
-
bean.getClass(), beanName, specificInterceptors,
new SingletonTargetSource(bean));
-
this.proxyTypes.put(cacheKey, proxy.getClass());
-
return proxy;
-
}
-
-
this.advisedBeans.put(cacheKey, Boolean.FALSE);
//加入advisedBeans集合中
-
return bean;
-
}
org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean
-
protected Object[] getAdvicesAndAdvisorsForBean(
//找到符合条件的通知
-
Class<?> beanClass, String beanName,
@Nullable TargetSource targetSource) {
-
-
List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
//找到合适的通知
-
if (advisors.isEmpty()) {
-
return DO_NOT_PROXY;
-
}
-
return advisors.toArray();
-
}
org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findEligibleAdvisors
-
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
-
List<Advisor> candidateAdvisors = findCandidateAdvisors();
//找候选的通知
-
List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
//找到能用的Advisor
-
extendAdvisors(eligibleAdvisors);
-
if (!eligibleAdvisors.isEmpty()) {
-
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
-
}
-
return eligibleAdvisors;
-
}
org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors
org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors
-
@Override
-
protected List<Advisor> findCandidateAdvisors() {
-
// Add all the Spring advisors found according to superclass rules.
-
List<Advisor> advisors =
super.findCandidateAdvisors();
//找到事务的增强器
-
// Build Advisors for all AspectJ aspects in the bean factory.
-
if (
this.aspectJAdvisorsBuilder !=
null) {
-
advisors.addAll(
this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
//buildAspectJAdvisors 找AspectJ的增强器
-
}
-
return advisors;
-
}
- 解析findCandidateAdvisors 步骤1.findAdvisorBeans
org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper#findAdvisorBeans
-
public List<Advisor> findAdvisorBeans() {
-
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(
//从IOC容器中找到所有实现Advisor的实现类的beanName
-
this.beanFactory, Advisor.class,
true,
false);
-
this.cachedAdvisorBeanNames = advisorNames;
//赋值给增强器缓存
-
}
-
if (advisorNames.length ==
0) {
//在IOC容器中没有获取到直接返回
-
return
new ArrayList<>();
-
}
-
-
List<Advisor> advisors =
new ArrayList<>();
-
for (String name : advisorNames) {
//遍历所有的通知(advisor)
-
if (isEligibleBean(name)) {
-
if (
this.beanFactory.isCurrentlyInCreation(name)) {
//忽略正在创建的advisor
-
if (logger.isDebugEnabled()) {
-
logger.debug(
"Skipping currently created advisor '" + name +
"'");
-
}
-
}
-
else {
-
try {
//通过getBean的形式创建通知(advisot) //并且将bean 添加到advisors中
-
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.isDebugEnabled()) {
-
logger.debug(
"Skipping advisor '" + name +
-
"' with dependency on currently created bean: " + ex.getMessage());
-
}
-
-
continue;
-
}
-
}
-
throw ex;
-
}
-
}
-
}
-
}
-
return advisors;
-
}
- 解析findCandidateAdvisors 步骤 2.buildAspectJAdvisors
org.springframework.aop.aspectj.annotation.BeanFactoryAspectJAdvisorsBuilder#buildAspectJAdvisors
-
public List<Advisor> buildAspectJAdvisors() {
-
List<String> aspectNames =
this.aspectBeanNames;
//从缓存中获取
-
-
if (aspectNames ==
null) {
//缓存中没有获取到
-
synchronized (
this) {
-
aspectNames =
this.aspectBeanNames;
//再次冲缓存中获取
-
if (aspectNames ==
null) {
-
List<Advisor> advisors =
new ArrayList<>();
-
aspectNames =
new ArrayList<>();
-
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
//找到所有的beanName
-
this.beanFactory, Object.class,
true,
false);
-
for (String beanName : beanNames) {
//遍历beanNames
-
if (!isEligibleBean(beanName)) {
-
continue;
-
}
-
-
Class<?> beanType =
this.beanFactory.getType(beanName);
//获取bean的类型
-
if (beanType ==
null) {
-
continue;
-
}
-
if (
this.advisorFactory.isAspect(beanType)) {
//判断是不是切面 源码
-
aspectNames.add(beanName);
-
AspectMetadata amd =
new AspectMetadata(beanType, beanName);
//创建Aspect类的源信息对象
-
if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
-
MetadataAwareAspectInstanceFactory factory =
-
new BeanFactoryAspectInstanceFactory(
this.beanFactory, beanName);
-
List<Advisor> classAdvisors =
this.advisorFactory.getAdvisors(factory);
//从aspectj中获取通知(advisor) 源码
-
if (
this.beanFactory.isSingleton(beanName)) {
-
this.advisorsCache.put(beanName, classAdvisors);
//key 类名 value 通知(advisor)
-
}
-
else {
-
this.aspectFactoryCache.put(beanName, factory);
-
}
-
advisors.addAll(classAdvisors);
-
}
-
else {
-
// Per target or per this.
-
if (
this.beanFactory.isSingleton(beanName)) {
-
throw
new IllegalArgumentException(
"Bean with name '" + beanName +
-
"' is a singleton, but aspect instantiation model is not singleton");
-
}
-
MetadataAwareAspectInstanceFactory factory =
-
new PrototypeAspectInstanceFactory(
this.beanFactory, beanName);
-
this.aspectFactoryCache.put(beanName, factory);
-
advisors.addAll(
this.advisorFactory.getAdvisors(factory));
-
}
-
}
-
}
-
this.aspectBeanNames = aspectNames;
-
return advisors;
-
}
-
}
-
}
-
-
if (aspectNames.isEmpty()) {
-
return Collections.emptyList();
//没有,则返回空
-
}
-
List<Advisor> advisors =
new ArrayList<>();
//缓存中有通知(Advisor) 从缓存中获取并返回
-
for (String aspectName : aspectNames) {
-
List<Advisor> cachedAdvisors =
this.advisorsCache.get(aspectName);
-
if (cachedAdvisors !=
null) {
-
advisors.addAll(cachedAdvisors);
-
}
-
else {
-
MetadataAwareAspectInstanceFactory factory =
this.aspectFactoryCache.get(aspectName);
-
advisors.addAll(
this.advisorFactory.getAdvisors(factory));
-
}
-
}
-
return advisors;
-
}
- 解析findCandidateAdvisors 步骤 3.getAdvisors
org.springframework.aop.aspectj.annotation.ReflectiveAspectJAdvisorFactory#getAdvisors
-
public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
-
Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
//获取标识了@AspectJ标志的切面类
-
String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
//获取切面的名称
-
validate(aspectClass);
-
-
MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =
-
new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);
-
-
List<Advisor> advisors =
new ArrayList<>();
-
for (Method method : getAdvisorMethods(aspectClass)) {
//获取切面类中的所有除了切点(@Pointcut注解)的方法,包括object方法
-
Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);
// 每个method获取通知(advisor) 源码
-
if (advisor !=
null) {
-
advisors.add(advisor);
-
}
-
}
-
-
-
if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
-
Advisor instantiationAdvisor =
new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);
-
advisors.add(
0, instantiationAdvisor);
-
}
-
-
// Find introduction fields.
-
for (Field field : aspectClass.getDeclaredFields()) {
-
Advisor advisor = getDeclareParentsAdvisor(field);
-
if (advisor !=
null) {
-
advisors.add(advisor);
-
}
-
}
-
-
return advisors;
-
}
-
-
-
//org.springframework.aop.aspectj.annotation.ReflectiveAspectJAdvisorFactory#getAdvisor
-
public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory,
-
int declarationOrderInAspect, String aspectName) {
-
-
validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());
-
//获取切点表达式 源码
-
AspectJExpressionPointcut expressionPointcut = getPointcut(
-
candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());
-
if (expressionPointcut ==
null) {
-
return
null;
-
}
-
//创建切面的实现类 源码
-
return
new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,
-
this, aspectInstanceFactory, declarationOrderInAspect, aspectName);
-
}
-
-
//org.springframework.aop.aspectj.annotation.ReflectiveAspectJAdvisorFactory#getPointcut
-
private AspectJExpressionPointcut getPointcut(Method candidateAdviceMethod, Class<?> candidateAspectClass) {
-
AspectJAnnotation<?> aspectJAnnotation =
//获取切面注解 @Before @After。。。。。。
-
AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
//源码
-
if (aspectJAnnotation ==
null) {
-
return
null;
-
}
-
//获取切点表达式对象
-
AspectJExpressionPointcut ajexp =
-
new AspectJExpressionPointcut(candidateAspectClass,
new String[
0],
new Class<?>[
0]);
-
ajexp.setExpression(aspectJAnnotation.getPointcutExpression());
//设置切点表达式
-
if (
this.beanFactory !=
null) {
-
ajexp.setBeanFactory(
this.beanFactory);
-
}
-
return ajexp;
-
}
-
-
-
-
/**
-
*org.springframework.aop.aspectj.annotation.InstantiationModelAwarePointcutAdvisorImpl#In*stantiationModelAwarePointcutAdvisorImpl
-
*/
-
-
public InstantiationModelAwarePointcutAdvisorImpl(AspectJExpressionPointcut declaredPointcut,
-
Method aspectJAdviceMethod, AspectJAdvisorFactory aspectJAdvisorFactory,
-
MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {
-
-
this.declaredPointcut = declaredPointcut;
-
this.declaringClass = aspectJAdviceMethod.getDeclaringClass();
-
this.methodName = aspectJAdviceMethod.getName();
-
this.parameterTypes = aspectJAdviceMethod.getParameterTypes();
-
this.aspectJAdviceMethod = aspectJAdviceMethod;
-
this.aspectJAdvisorFactory = aspectJAdvisorFactory;
-
this.aspectInstanceFactory = aspectInstanceFactory;
-
this.declarationOrder = declarationOrder;
-
this.aspectName = aspectName;
-
-
if (aspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
//是不是懒加载
-
// Static part of the pointcut is a lazy type.
-
Pointcut preInstantiationPointcut = Pointcuts.union(
-
aspectInstanceFactory.getAspectMetadata().getPerClausePointcut(),
this.declaredPointcut);
-
-
// Make it dynamic: must mutate from pre-instantiation to post-instantiation state.
-
// If it's not a dynamic pointcut, it may be optimized out
-
// by the Spring AOP infrastructure after the first evaluation.
-
this.pointcut =
new PerTargetInstantiationModelPointcut(
-
this.declaredPointcut, preInstantiationPointcut, aspectInstanceFactory);
-
this.lazy =
true;
-
}
-
else {
-
// A singleton aspect.
-
this.pointcut =
this.declaredPointcut;
-
this.lazy =
false;
-
this.instantiatedAdvice = instantiateAdvice(
this.declaredPointcut);
//实例化切面 源码
-
}
-
}
-
-
/**
-
*org.springframework.aop.aspectj.annotation.ReflectiveAspectJAdvisorFactory#getAdvice
-
*
-
*/
-
-
public Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut expressionPointcut,
-
MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {
-
-
Class<?> candidateAspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
//1.找到候选的切面类
-
validate(candidateAspectClass);
-
-
AspectJAnnotation<?> aspectJAnnotation =
-
AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
//找到方法上的注解
-
if (aspectJAnnotation ==
null) {
-
return
null;
-
}
-
-
// If we get here, we know we have an AspectJ method.
-
// Check that it's an AspectJ-annotated class
-
if (!isAspect(candidateAspectClass)) {
-
throw
new AopConfigException(
"Advice must be declared inside an aspect type: " +
-
"Offending method '" + candidateAdviceMethod +
"' in class [" +
-
candidateAspectClass.getName() +
"]");
-
}
-
-
if (logger.isDebugEnabled()) {
-
logger.debug(
"Found AspectJ method: " + candidateAdviceMethod);
-
}
-
-
AbstractAspectJAdvice springAdvice;
-
//判断注解的类型
-
switch (aspectJAnnotation.getAnnotationType()) {
-
case AtPointcut:
//是切点的返回null
-
if (logger.isDebugEnabled()) {
-
logger.debug(
"Processing pointcut '" + candidateAdviceMethod.getName() +
"'");
-
}
-
return
null;
-
case AtAround:
//是不是环绕通知
-
springAdvice =
new AspectJAroundAdvice(
-
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
-
break;
-
case AtBefore:
//是不是后置通知
-
springAdvice =
new AspectJMethodBeforeAdvice(
-
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
-
break;
-
case AtAfter:
//后置通知
-
springAdvice =
new AspectJAfterAdvice(
-
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
-
break;
-
case AtAfterReturning:
//返回通知
-
springAdvice =
new AspectJAfterReturningAdvice(
-
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
-
AfterReturning afterReturningAnnotation = (AfterReturning) aspectJAnnotation.getAnnotation();
-
if (StringUtils.hasText(afterReturningAnnotation.returning())) {
-
springAdvice.setReturningName(afterReturningAnnotation.returning());
-
}
-
break;
-
case AtAfterThrowing:
//是不是异常通知
-
springAdvice =
new AspectJAfterThrowingAdvice(
-
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
-
AfterThrowing afterThrowingAnnotation = (AfterThrowing) aspectJAnnotation.getAnnotation();
-
if (StringUtils.hasText(afterThrowingAnnotation.throwing())) {
-
springAdvice.setThrowingName(afterThrowingAnnotation.throwing());
-
}
-
break;
-
default:
-
throw
new UnsupportedOperationException(
-
"Unsupported advice type on method: " + candidateAdviceMethod);
-
}
-
-
// Now to configure the advice...
-
springAdvice.setAspectName(aspectName);
-
springAdvice.setDeclarationOrder(declarationOrder);
-
String[] argNames =
this.parameterNameDiscoverer.getParameterNames(candidateAdviceMethod);
//获取方法的参数列表名称
-
if (argNames !=
null) {
-
springAdvice.setArgumentNamesFromStringArray(argNames);
//为切面设置参数
-
}
-
springAdvice.calculateArgumentBindings();
-
-
return springAdvice;
-
}
org.springframework.aop.support.AopUtils#findAdvisorsThatCanApply
-
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
-
if (candidateAdvisors.isEmpty()) {
-
return candidateAdvisors;
-
}
-
List<Advisor> eligibleAdvisors =
new ArrayList<>();
-
for (Advisor candidate : candidateAdvisors) {
//遍历候选的通知 把他增加到eligibleAdvisors集合中返回
-
if (candidate
instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
////判断是当前的通知是否能用 通过方法匹配来计算当前是否合适当前类的增强器 源码
-
eligibleAdvisors.add(candidate);
-
}
-
}
-
boolean hasIntroductions = !eligibleAdvisors.isEmpty();
-
for (Advisor candidate : candidateAdvisors) {
-
if (candidate
instanceof IntroductionAdvisor) {
-
// already processed
-
continue;
-
}
-
if (canApply(candidate, clazz, hasIntroductions)) {
-
eligibleAdvisors.add(candidate);
-
}
-
}
-
return eligibleAdvisors;
-
}
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy
-
protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
-
@Nullable Object[] specificInterceptors, TargetSource targetSource) {
-
-
if (
this.beanFactory
instanceof ConfigurableListableBeanFactory) {
//判断类型
-
AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory)
this.beanFactory, beanName, beanClass);
-
}
-
-
ProxyFactory proxyFactory =
new ProxyFactory();
//创建代理工厂
-
proxyFactory.copyFrom(
this);
-
-
if (!proxyFactory.isProxyTargetClass()) {
//proxyTargetClass 强制使用cglib代理
-
if (shouldProxyTargetClass(beanClass, beanName)) {
-
proxyFactory.setProxyTargetClass(
true);
-
}
-
else {
-
evaluateProxyInterfaces(beanClass, proxyFactory);
-
}
-
}
-
-
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
////获取容器中的方法通知
-
proxyFactory.addAdvisors(advisors);
-
proxyFactory.setTargetSource(targetSource);
-
customizeProxyFactory(proxyFactory);
-
-
proxyFactory.setFrozen(
this.freezeProxy);
-
if (advisorsPreFiltered()) {
-
proxyFactory.setPreFiltered(
true);
-
}
-
-
return proxyFactory.getProxy(getProxyClassLoader());
//获取代理对象 源码
-
}
流程图
看了以上代码,我们画个加单的图来看一下aop创建代理对象的过程
转载:https://blog.csdn.net/qq_38630810/article/details/105565239