先了解下Spring Aop的几个概念
Aspect:切面,我们用注解配置aop的话就是加了@Aspect注解的类
Join point:连接点:程序执行过程中的一个点,也就是被代理接口或类的方法的执行
Advice:增强,通过@Before,@Around注解定义的方法,Spring会在连接点建立一个拦截器链,增强围绕着连接点进行的
Pointcut:切点,也就是匹配连接点的表达式
Introduction:不修改代理对象的代码,从而增加额外的行为
Target :目标对象,也就是被代理的对象,可以通过连接点point.getTarget()来获取到对应的代理对象
AOP Proxy:aop所使用的代理方式,jdk动态代理,cglib动态代理
Weaving:织入,运行时在执行增强的代码
通知类型:
Before advice: 在连接点之前运行,不能阻止连接点的运行,除非抛出异常
After returning advice: 在连接点正常完成后运行的通知,连接点方法没有抛出异常
After throwing advice: 方法抛出异常会执行此通知
After (finally) advice: 无论连接点以何种方式退出(正常或异常返回),都将运行通知
Around advice: 围绕连接点的建议,例如方法调用。环绕通知可以在方法调用之前和之后执行自定义行为。它还负责选择是继续到连接点还是通过返回自己的返回值或抛出异常来缩短建议的方法执行
Springboot Aop自动装配博客地址:SpringBoot Aop自动装配源码解析_LouD_dm的博客-CSDN博客
Springboo中默认使用注解的aop配置,自动装配的类是:AnnotationAwareAspectJAutoProxyCreator

AnnotationAwareAspectJAutoProxyCreator:springboot默认自动装配的类,处理加了@Aspect注解的类
AspectJAwareAdvisorAutoProxyCreator:暴露 AspectJ 的调用上下文并理解 AspectJ 规则的子类
AbstractAdvisorAutoProxyCreator:为特定 bean 构建 AOP 代理的通用自动代理创建器
AbstractAutoProxyCreator:BeanPostProcessor实现,使用 AOP 代理包装每个符合条件的 bean,委托给指定的拦截器
ProxyProcessorSupport:具有代理处理器通用功能的基类,特别是ClassLoader 管理和 {link #evaluateProxyInterfaces} 算法。
ProxyConfig:用于创建代理的配置的便利超类, 确保所有代理创建者具有一致的属性。
AopInfrastructureBean:实现此接口的类不被代理
SmartInstantiationAwareBeanPostProcessor:用于预测已处理Bean最终类型的回调
InstantiationAwareBeanPostProcessor:实现了BeanPostProcessor接口,增加Bean初始化前后的回调
BeanPostProcessor:Bean后置处理器,Spring初始化Bean时会调用注册的Bean后置处理器
Advice增强

Advisor建议(一个切面可以包含多个建议,多个建议里包含通知,切点)

首先看核心类 AbstractAutoProxyCreator,这个类实现了SmartInstantiationAwareBeanPostProcessor接口,意味着Spring中bean的初始化前后会调用SmartInstantiationAwareBeanPostProcessor后置处理器的方法
AbstractAutoProxyCreator重写了postProcessBeforeInstantiation,getEarlyBeanReference方法
postProcessBeforeInstantiation和postProcessAfterInstantiation在bean初始化前还没有调用填充属性之前执行
getEarlyBeanReference在bean填充属性之前,初始化调用postProcessBeforeInstantiation之后
1)首先看postProcessBeforeInstantiation方法,如果自定义TargetSource可以提前生成代理,
这里getAdvicesAndAdvisorsForBean收集所有的Advisor(建议),之后调用createProxy创建bean的代理
- @Override
- public Object postProcessBeforeInstantiation(Class> beanClass, String beanName) {
- Object cacheKey = getCacheKey(beanClass, beanName);
-
- if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
- if (this.advisedBeans.containsKey(cacheKey)) {
- return null;
- }
- if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
- this.advisedBeans.put(cacheKey, Boolean.FALSE);
- return null;
- }
- }
-
- // 如果我们有自定义 TargetSource,请在此处创建代理。
- // 抑制目标 bean 的不必要的默认实例化:
- // TargetSource 将以自定义方式处理目标实例。
- TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
- if (targetSource != null) {
- 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;
- }
getEarlyBeanReference方法同样也是收集Advisor,创建代理,只不过一个是自定义targetSource,一个是使用的SingletonTargetSource
- @Override
- public Object getEarlyBeanReference(Object bean, String beanName) {
- Object cacheKey = getCacheKey(bean.getClass(), beanName);
- this.earlyProxyReferences.put(cacheKey, bean);
- return wrapIfNecessary(bean, beanName, cacheKey);
- }
-
- /**
- * 如有必要,包装给定的 bean,即如果它有资格被代理。
- *
- * @param bean the raw bean instance
- * @param beanName the name of the bean
- * @param cacheKey the cache key for metadata access
- * @return a proxy wrapping the bean, or the raw bean instance as-is
- */
- 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)) {
- this.advisedBeans.put(cacheKey, Boolean.FALSE);
- return bean;
- }
-
- // 如果我们有建议,请创建代理.
- // 获取bean所有的Advisor
- Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
- if (specificInterceptors != DO_NOT_PROXY) {
- this.advisedBeans.put(cacheKey, Boolean.TRUE);
- //创建对应的代理,使用SingletonTargetSource
- Object proxy = createProxy(
- bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
- this.proxyTypes.put(cacheKey, proxy.getClass());
- return proxy;
- }
-
- this.advisedBeans.put(cacheKey, Boolean.FALSE);
- return bean;
- }
子类AbstractAdvisorAutoProxyCreator实现了getAdvicesAndAdvisorsForBean收集建议的方法
- @Override
- @Nullable
- protected Object[] getAdvicesAndAdvisorsForBean(
- Class> beanClass, String beanName, @Nullable TargetSource targetSource) {
-
- List
advisors = findEligibleAdvisors(beanClass, beanName); - if (advisors.isEmpty()) {
- return DO_NOT_PROXY;
- }
- return advisors.toArray();
- }
-
- /**
- * 查找所有符合条件的顾问以自动代理此类。
- * @param beanClass the clazz to find advisors for
- * @param beanName the name of the currently proxied bean
- * @return the empty List, not {@code null},
- * if there are no pointcuts or interceptors
- * @see #findCandidateAdvisors
- * @see #sortAdvisors
- * @see #extendAdvisors
- */
- protected List
findEligibleAdvisors(Class> beanClass, String beanName) { - //获取所有的Advisor
- List
candidateAdvisors = findCandidateAdvisors(); - //根据当前bean做筛选
- List
eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); - extendAdvisors(eligibleAdvisors);
- if (!eligibleAdvisors.isEmpty()) {
- eligibleAdvisors = sortAdvisors(eligibleAdvisors);
- }
- return eligibleAdvisors;
- }
findCandidateAdvisors方法调用的advisorRetrievalHelper来查找bean
- /**
- * 查找要在自动代理中使用的所有候选顾问。
- * @return the List of candidate Advisors
- */
- protected List
findCandidateAdvisors() { - Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
- return this.advisorRetrievalHelper.findAdvisorBeans();
- }
advisorRetrievalHelper.findAdvisorBeans方法从spring中查找advisor类型的bean返回
- /**
- * 查找当前 bean factory 中所有符合条件的 Advisor bean,
- * 忽略 FactoryBeans 并排除当前正在创建的 bean。
- *
- * @return the list of {@link org.springframework.aop.Advisor} beans
- * @see #isEligibleBean
- */
- public List
findAdvisorBeans() { - // 确定顾问 bean 名称列表(如果尚未缓存)。
- String[] advisorNames = this.cachedAdvisorBeanNames;
- if (advisorNames == null) {
- // 不要在此处初始化 FactoryBeans:我们需要保留所有常规 bean
- // 未初始化以让自动代理创建者应用到它们!
- advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
- this.beanFactory, Advisor.class, true, false);
- this.cachedAdvisorBeanNames = advisorNames;
- }
- if (advisorNames.length == 0) {
- return new ArrayList<>();
- }
-
- List
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;
- }
筛选对应的bean
- /**
- * 搜索给定的候选顾问以查找所有符合条件的顾问
- * 可以应用于指定的bean。
- *
- * @param candidateAdvisors the candidate Advisors
- * @param beanClass the target's bean class
- * @param beanName the target's bean name
- * @return the List of applicable Advisors
- * @see ProxyCreationContext#getCurrentProxiedBeanName()
- */
- protected List
findAdvisorsThatCanApply( - List
candidateAdvisors, Class> beanClass, String beanName) { -
- ProxyCreationContext.setCurrentProxiedBeanName(beanName);
- try {
- return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
- } finally {
- ProxyCreationContext.setCurrentProxiedBeanName(null);
- }
- }
筛选出类型是IntroductionAdvisor,并且适配当前bean的Advisor
- /**
- * 确定 {code CandidateAdvisors} 列表的子列表
- * 适用于给定类。
- *
- * @param candidateAdvisors the Advisors to evaluate
- * @param clazz the target class
- * @return sublist of Advisors that can apply to an object of the given class
- * (may be the incoming List as-is)
- */
- public static List
findAdvisorsThatCanApply(List candidateAdvisors, Class> clazz) { - if (candidateAdvisors.isEmpty()) {
- return candidateAdvisors;
- }
- List
eligibleAdvisors = new ArrayList<>(); - for (Advisor candidate : candidateAdvisors) {
- 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;
- }
-
- /**
- * 给定的顾问可以完全适用于给定的课程吗?
- * 这是一个重要的测试,因为它可以用来优化
- * 出一个班级的顾问。
- *
- * @param advisor the advisor to check
- * @param targetClass class we're testing
- * @return whether the pointcut can apply on any method
- */
- public static boolean canApply(Advisor advisor, Class> targetClass) {
- return canApply(advisor, targetClass, false);
- }
-
- /**
- * 给定的顾问可以完全适用于给定的课程吗?
- *
这是一个重要的测试,因为它可以用来优化一个类的顾问。
- * 此版本还考虑了介绍(对于 IntroductionAwareMethodMatchers)。
- *
- * @param advisor the advisor to check
- * @param targetClass class we're testing
- * @param hasIntroductions whether or not the advisor chain for this bean includes
- * any introductions
- * @return whether the pointcut can apply on any method
- */
- public static boolean canApply(Advisor advisor, Class> targetClass, boolean hasIntroductions) {
- if (advisor instanceof IntroductionAdvisor) {
- return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
- } else if (advisor instanceof PointcutAdvisor) {
- PointcutAdvisor pca = (PointcutAdvisor) advisor;
- return canApply(pca.getPointcut(), targetClass, hasIntroductions);
- } else {
- // It doesn't have a pointcut so we assume it applies.
- return true;
- }
- }
接着回到findCandidateAdvisors方法,上面的流程是找Advisor类型的bean
- @Override
- protected List
findCandidateAdvisors() { - // 添加根据超类规则找到的所有 Spring 顾问。
- List
advisors = super.findCandidateAdvisors(); - // 为 bean 工厂中的所有 AspectJ 方面构建顾问。
- if (this.aspectJAdvisorsBuilder != null) {
- advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
- }
- return advisors;
- }
下一步aspectJAdvisorsBuilder不为空的话执行下面的方法,AbstractAutoProxyCreator实现了BeanFactoryAware,bean初始化会调用setBeanFactory接口,AbstractAdvisorAutoProxyCreator重写了setBeanFactory接口,并调用了initBeanFactory方法自定义初始化BeanFactory,这里面已经初始化了aspectJAdvisorsBuilder 这个属性
- @Override
- public void setBeanFactory(BeanFactory beanFactory) {
- super.setBeanFactory(beanFactory);
- if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
- throw new IllegalArgumentException(
- "AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory);
- }
- initBeanFactory((ConfigurableListableBeanFactory) beanFactory);
- }
- @Override
- protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
- super.initBeanFactory(beanFactory);
- if (this.aspectJAdvisorFactory == null) {
- this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);
- }
- this.aspectJAdvisorsBuilder =
- new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);
- }
BeanFactoryAdvisorRetrievalHelperAdapter的buildAspectJAdvisors方法,从容器中找到所有的bean名称,根据bean的class上是否加了Aspect来判断是否是切面,一般使用的切面都是单例类型的,之后包装一下切面的bean,从切面里找对应的Advisor,
- public List
buildAspectJAdvisors() { - List
aspectNames = this.aspectBeanNames; -
- if (aspectNames == null) {
- synchronized (this) {
- aspectNames = this.aspectBeanNames;
- if (aspectNames == null) {
- List
advisors = new ArrayList<>(); - aspectNames = new ArrayList<>();
- String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
- this.beanFactory, Object.class, true, false);
- for (String beanName : beanNames) {
- if (!isEligibleBean(beanName)) {
- continue;
- }
- // 我们必须小心不要急切地实例化 bean,因为在这种情况下它们
- // 将被 Spring 容器缓存但不会被编织。
- Class> beanType = this.beanFactory.getType(beanName);
- if (beanType == null) {
- continue;
- }
- if (this.advisorFactory.isAspect(beanType)) {
- aspectNames.add(beanName);
- AspectMetadata amd = new AspectMetadata(beanType, beanName);
- if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
- MetadataAwareAspectInstanceFactory factory =
- new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
- List
classAdvisors = this.advisorFactory.getAdvisors(factory); - if (this.beanFactory.isSingleton(beanName)) {
- this.advisorsCache.put(beanName, classAdvisors);
- } 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
advisors = new ArrayList<>(); - for (String aspectName : aspectNames) {
- List
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;
- }
判断是否是切面
- /**
- * 我们认为某些东西是适合 Spring AOP 系统使用的 AspectJ 方面
- * 如果它有 Aspect 注释,并且不是由 ajc 编译的。后一个测试的原因
- * 是以代码风格(AspectJ 语言)编写的方面也存在注释
- * 当带有 -1.5 标志的 ajc 编译时,它们不能被 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);
- }
-
- /**
- * 我们需要将其检测为“代码风格”的 AspectJ 方面不应该
- * 由 Spring AOP 解释。
- */
- private boolean compiledByAjc(Class> clazz) {
- // AJTypeSystem 竭尽全力在代码风格和
- // 注释样式方面。因此,没有“干净”的方法可以区分它们。在这里我们依靠
- // AspectJ 编译器的实现细节。
- for (Field field : clazz.getDeclaredFields()) {
- if (field.getName().startsWith(AJC_MAGIC)) {
- return true;
- }
- }
- return false;
- }
根据bean查找Advisor,找对应class下面所有没有Pointcut注解的方法,之后根据方法找到对应
- @Override
- public List
getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) { - Class> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
- String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
- validate(aspectClass);
-
- // 我们需要用装饰器包装 MetadataAwareAspectInstanceFactory
- // 这样它只会实例化一次。
- MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =
- new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);
-
- List
advisors = new ArrayList<>(); - for (Method method : getAdvisorMethods(aspectClass)) {
- Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);
- if (advisor != null) {
- advisors.add(advisor);
- }
- }
-
- //懒加载处理
- if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
- Advisor instantiationAdvisor = new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);
- advisors.add(0, instantiationAdvisor);
- }
-
- // 查找介绍字段.
- for (Field field : aspectClass.getDeclaredFields()) {
- Advisor advisor = getDeclareParentsAdvisor(field);
- if (advisor != null) {
- advisors.add(advisor);
- }
- }
-
- return advisors;
- }
获取没有加Pointcut的方法,从方法里获取Advisor,也就是加了Pointcut.class, Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class注解的方法,封装为InstantiationModelAwarePointcutAdvisorImpl
- private List
getAdvisorMethods(Class> aspectClass) { - final List
methods = new ArrayList<>(); - ReflectionUtils.doWithMethods(aspectClass, method -> {
- // Exclude pointcuts
- if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) {
- methods.add(method);
- }
- }, ReflectionUtils.USER_DECLARED_METHODS);
- methods.sort(METHOD_COMPARATOR);
- return methods;
- }
-
- @Override
- @Nullable
- 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);
- }
-
- @Nullable
- private AspectJExpressionPointcut getPointcut(Method candidateAdviceMethod, Class> candidateAspectClass) {
- AspectJAnnotation> aspectJAnnotation =
- 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;
- }
- private static final Class>[] ASPECTJ_ANNOTATION_CLASSES = new Class>[]{
- Pointcut.class, Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class};
-
- @Nullable
- protected static AspectJAnnotation> findAspectJAnnotationOnMethod(Method method) {
- for (Class> clazz : ASPECTJ_ANNOTATION_CLASSES) {
- AspectJAnnotation> foundAnnotation = findAnnotation(method, (Class
) clazz); - if (foundAnnotation != null) {
- return foundAnnotation;
- }
- }
- return null;
- }
创建InstantiationModelAwarePointcutAdvisorImpl的构造方法,如果是单例找对应的通知,主要方法instantiateAdvice
- 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()) {
- // 切入点的静态部分是惰性类型。
- Pointcut preInstantiationPointcut = Pointcuts.union(
- aspectInstanceFactory.getAspectMetadata().getPerClausePointcut(), this.declaredPointcut);
-
- //使其动态化:必须从实例化前状态转变为实例化后状态。
- // 如果不是动态切入点,可能会被优化掉
- // 在第一次评估之后由 Spring AOP 基础设施。
- 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);
- }
- }
从Advisor找对应的Advice,根据注解不同创建不同的Advice实现
- private Advice instantiateAdvice(AspectJExpressionPointcut pointcut) {
- Advice advice = this.aspectJAdvisorFactory.getAdvice(this.aspectJAdviceMethod, pointcut,
- this.aspectInstanceFactory, this.declarationOrder, this.aspectName);
- return (advice != null ? advice : EMPTY_ADVICE);
- }
-
- @Override
- @Nullable
- public Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut expressionPointcut,
- MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {
-
- Class> candidateAspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
- validate(candidateAspectClass);
-
- AspectJAnnotation> aspectJAnnotation =
- AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
- if (aspectJAnnotation == null) {
- return null;
- }
-
- //如果我们到达这里,我们知道我们有一个 AspectJ 方法。
- // 检查它是否是一个 AspectJ 注释的类
- 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:
- 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);
- }
-
- // 现在配置建议...
- springAdvice.setAspectName(aspectName);
- springAdvice.setDeclarationOrder(declarationOrder);
- String[] argNames = this.parameterNameDiscoverer.getParameterNames(candidateAdviceMethod);
- if (argNames != null) {
- springAdvice.setArgumentNamesFromStringArray(argNames);
- }
- springAdvice.calculateArgumentBindings();
-
- return springAdvice;
- }
我们常用的注解实现的Aop,就是spring在bean初始化时看bean的class上是否加了切面的注解,如果加了,会找切面下的Advisor,每一个加了Pointcut.class, Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class注解的方法和切点会被封装为一个Advisor,Advisor里有对应的通知,spring会根据注解的不同创建不同的通知。
有些地方还没看懂,之后在慢慢了解,之后就是Spring怎么根据Advisor创建对应bean的代理