Aop源码

1.准备

aspect

@Component
@Aspect
@Slf4j
public class LogAspect {

    private static final String POINT_CUT =
            "execution(public void com.tca.spring.framework.learning.aop.source.service.LogService.*(..))";

    @Pointcut(value = POINT_CUT)
    private void pointCut() {}

    @Before(value = "pointCut()")
    public void logBefore(JoinPoint joinPoint) {
        log.info("调用方法: {}, 入参: {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }
}

service

@Component
@Slf4j
public class LogService {

    public void log(String name, String word) {
        log.info("hello, {}, {}", name, word);
    }
}

config主配置

@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.tca.spring.framework.learning.aop.source")
public class AopConfig {
}

启动类

public class AopStarter {

    public static void main(String[] args) {
        ApplicationContext ac = new AnnotationConfigApplicationContext(AopConfig.class);
        LogService logService = ac.getBean(LogService.class);
        logService.log("Messi", "welcome");
    }
}

2.@EnableAspectJAutoProxy解析

2.1 @EnableAspectJAutoProxy

在主配置类上添加了@EnableAspectJAutoProxy注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {

	/**
	 * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
	 * to standard Java interface-based proxies. The default is {@code false}.
	 * 是否使用cglib动态代理, 默认为false, 使用jdk动态代理
	 */
	boolean proxyTargetClass() default false;

	/**
	 * Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal}
	 * for retrieval via the {@link org.springframework.aop.framework.AopContext} class.
	 * Off by default, i.e. no guarantees that {@code AopContext} access will work.
	 * @since 4.3.1
	 */
	boolean exposeProxy() default false;

}

当前注解中@Import(AspectJAutoProxyRegistrar.class), 即在spring容器中引入了AspectJAutoProxyRegistrar,这个AspectJAutoProxyRegistrar何时被扫描到spring容器?

1.在@spring源码解析中, 我们知道, 在spring容器启动时, refresh()方法的第五步, invokeBeanFactoryPostProcessors(beanFactory)方法中, 会创建ConfigurationClassPostProcessor, 这个Bean实现了BeanDefinitionRegistryPostProcessor接口, 和BeanDefinitionRegistryPostProcessor接口的父接口BeanFactoryPostProcessor;
2.在当前方法中, 会调用ConfigurationClassPostProcessor的processConfigBeanDefinitions(registry)方法, 解析主配置类, 把扫描的类和@Bean以及@Import的类扫描并封装成BeanDefinition, 放到spring容器中
3.具体的代码在ConfigurationClassParser#doProcessConfigurationClass(ConfigurationClass, SourceClass):
	// Process any @Import annotations
	processImports(configClass, sourceClass, getImports(sourceClass), true);

2.2 ConfigurationClassPostProcessor#processConfigBeanDefinitions(registry)

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
    List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
    // 1.这里获取的candidateNames一共有6个, 一个自定义的mainConfig, 5个内置的
    String[] candidateNames = registry.getBeanDefinitionNames();
	
    for (String beanName : candidateNames) {
        BeanDefinition beanDef = registry.getBeanDefinition(beanName);
        // 2.上述6个都不满足以下条件
        // 内部有两个标记位来标记是否已经处理过了: isFullConfigurationClass, isLiteConfigurationClass
        // 当我们注册配置类的时候,可以不加@Configuration注解,直接使用@Component @ComponentScan @Import @ImportResource注解,称之为Lite配置类
        // 如果加了@Configuration注解,就称之为Full配置类
        // 如果我们注册了Lite配置类,我们getBean这个配置类,会发现它就是原本的那个配置类
        // 如果我们注册了Full配置类,我们getBean这个配置类,会发现它已经不是原本那个配置类了,而是已经被cgilb代理的类了
        if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
            ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
            }
        }
        // 3.自定义的mainConfig满足下面条件: 同时修改MainConfig为Full配置类
        else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
            configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
        }
    }
    // 4.校验, 此时不为空, 跳过
    if (configCandidates.isEmpty()) {
        return;
    }
    // 5.根据@Order标签排序
    configCandidates.sort((bd1, bd2) -> {
        int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
        int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
        return Integer.compare(i1, i2);
    });
    SingletonBeanRegistry sbr = null;
    // 6.DefaultListableBeanFactory会实现SingletonBeanRegistry接口, 进入
    if (registry instanceof SingletonBeanRegistry) {
        sbr = (SingletonBeanRegistry) registry;
        if (!this.localBeanNameGeneratorSet) {
            BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
            // 7.为空, 直接跳过
            if (generator != null) {
                this.componentScanBeanNameGenerator = generator;
                this.importBeanNameGenerator = generator;
            }
        }
    }
	// 8.跳过
    if (this.environment == null) {
        this.environment = new StandardEnvironment();
    }
	// 9.解析所有@Configuration的类!!!!!!
    // 9.1 创建@Configuration配置类解析器
    ConfigurationClassParser parser = new ConfigurationClassParser(
        this.metadataReaderFactory, this.problemReporter, this.environment,
        this.resourceLoader, this.componentScanBeanNameGenerator, registry);
	// 9.2 需要被ConfigurationClassParser解析的类
    Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
    // 9.3 已经被ConfigurationClassParser解析的类
    Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
    do {
        // 9.4 这个方法极其重要!!!解析@Configuration类
        parser.parse(candidates);
        // 9.5 校验
        parser.validate();
		// 9.6 获取解析完成后的MainConfig对应的ConfigurationClass
        // 注意:这里获取到的configClasses有三个: logAspect、aopConfig、logService, 即所有被扫描的类都会被封装成ConfigurationClass
        Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
        configClasses.removeAll(alreadyParsed);
        // Read the model and create bean definitions based on its content
        if (this.reader == null) {
            // 9.7 创建 ConfigurationClassBeanDefinitionReader 对象
            this.reader = new ConfigurationClassBeanDefinitionReader(
                registry, this.sourceExtractor, this.resourceLoader, this.environment,
                this.importBeanNameGenerator, parser.getImportRegistry());
        }
        // 9.8 【重点方法】, 见@2.5
        this.reader.loadBeanDefinitions(configClasses);
        // 9.9 解析MainConfig完成, 添加到已解析列表中
        alreadyParsed.addAll(configClasses);

        candidates.clear();
        // 9.10 这里beanDefiniton新添加了一个, student对应的BeanDefinition, 大于candidateNames.length
        if (registry.getBeanDefinitionCount() > candidateNames.length) {
            String[] newCandidateNames = registry.getBeanDefinitionNames();
            Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
            Set<String> alreadyParsedClasses = new HashSet<>();
            for (ConfigurationClass configurationClass : alreadyParsed) {
                alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
            }
            for (String candidateName : newCandidateNames) {
                if (!oldCandidateNames.contains(candidateName)) {
                    BeanDefinition bd = registry.getBeanDefinition(candidateName);
                    if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
                        !alreadyParsedClasses.contains(bd.getBeanClassName())) {
                        candidates.add(new BeanDefinitionHolder(bd, candidateName));
                    }
                }
            }
            candidateNames = newCandidateNames;
        }
    }
    while (!candidates.isEmpty());
	// 暂略
    // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
    if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
        sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
    }
	// 暂略
    if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
        // Clear cache in externally provided MetadataReaderFactory; this is a no-op
        // for a shared cache since it'll be cleared by the ApplicationContext.
        ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
    }
}

2.3 ConfigurationClassParser#getImport(SourceClass)

private Set<SourceClass> getImports(SourceClass sourceClass) throws IOException {
    Set<SourceClass> imports = new LinkedHashSet<>();
    Set<SourceClass> visited = new LinkedHashSet<>();
    collectImports(sourceClass, imports, visited);
    return imports;
}
private void collectImports(SourceClass sourceClass, Set<SourceClass> imports, Set<SourceClass> visited)
    throws IOException {

    if (visited.add(sourceClass)) {
        // 递归解析配置类的@Import
        // 获取配置类的注解, 判断注解中是否包含@Import, 有则添加, 没有则判断注解中的源码是否包含@Import, 有则添加
        for (SourceClass annotation : sourceClass.getAnnotations()) {
            String annName = annotation.getMetadata().getClassName();
            if (!annName.equals(Import.class.getName())) {
                collectImports(annotation, imports, visited);
            }
        }
        imports.addAll(sourceClass.getAnnotationAttributes(Import.class.getName(), "value"));
    }
}

2.4 ConfigurationClassParser#processImports(ConfigurationClass, SourceClass, Collection , boolean)

private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
                            Collection<SourceClass> importCandidates, boolean checkForCircularImports) {
	// 1.这里的 importCandidates 中包含了上面@Import扫描的类: AspectJAutoProxyRegistrar
    if (importCandidates.isEmpty()) {
        return;
    }
	// 2.跳过
    if (checkForCircularImports && isChainedImportOnStack(configClass)) {
        this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
    }
    else {
        this.importStack.push(configClass);
        try {
            // 3.这里的candidate只有一个: AspectJAutoProxyRegistrar
            for (SourceClass candidate : importCandidates) {
                // 4.AspectJAutoProxyRegistrar没有继承 ImportSelector, 跳过
                if (candidate.isAssignable(ImportSelector.class)) {
                    // Candidate class is an ImportSelector -> delegate to it to determine imports
                    Class<?> candidateClass = candidate.loadClass();
                    ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class);
                    ParserStrategyUtils.invokeAwareMethods(
                        selector, this.environment, this.resourceLoader, this.registry);
                    if (selector instanceof DeferredImportSelector) {
                        this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
                    }
                    else {
                        String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
                        Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);
                        processImports(configClass, currentSourceClass, importSourceClasses, false);
                    }
                }
                // 5.AspectJAutoProxyRegistrar实现了ImportBeanDefinitionRegistrar接口, 这里需要进入
                else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
                    // Candidate class is an ImportBeanDefinitionRegistrar ->
                    // delegate to it to register additional bean definitions
                    // 6.获取class对象 --> AspectJAutoProxyRegistrar.class
                    Class<?> candidateClass = candidate.loadClass();
                    // 7.注意: 这里没有将AspectJAutoProxyRegistrar封装成BeanDefinition, 放到BeanDefinitionMap中, 而是直接实例化对象
                    ImportBeanDefinitionRegistrar registrar =
                        BeanUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class);
                    // 8.跳过
                    ParserStrategyUtils.invokeAwareMethods(
                        registrar, this.environment, this.resourceLoader, this.registry);
                    // 9.将(registrar, metadata)存储到当前configClass --> aopConfig的importBeanDefinitionRegistrars属性中(map), 后面会使用
                    configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
                }
                else {
                    // Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
                    // process it as an @Configuration class
                    this.importStack.registerImport(
                        currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
                    processConfigurationClass(candidate.asConfigClass(configClass));
                }
            }
        }
        catch (BeanDefinitionStoreException ex) {
            throw ex;
        }
        catch (Throwable ex) {
            throw new BeanDefinitionStoreException(
                "Failed to process import candidates for configuration class [" +
                configClass.getMetadata().getClassName() + "]", ex);
        }
        finally {
            this.importStack.pop();
        }
    }
}

2.5 ConfigurationClassBeanDefinitionReader#loadBeanDefinitions(Set)

// 这里传入的Set<ConfigurationClass>为: logAspect、aopConfig、logService对应的ConfigurationClass
public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
    TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator();
    for (ConfigurationClass configClass : configurationModel) {
        // 对于 logAspect、logService, 这里可以忽略
        // 对于 aopConfig, 这里需要解析, 在@2.4中, 解析aopConfig时, 会创建AspectJAutoProxyRegistrar对象, 并且将(AspectJAutoProxyRegistrar对象, aopConfig的注解metadata)存储到aopConfig对应的ConfigurationClass的importBeanDefinitionRegistrars属性中(map)
        loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator);
    }
}
private void loadBeanDefinitionsForConfigurationClass(
    ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) {
	// 1.跳过
    if (trackedConditionEvaluator.shouldSkip(configClass)) {
        String beanName = configClass.getBeanName();
        if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) {
            this.registry.removeBeanDefinition(beanName);
        }
        this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName());
        return;
    }

    if (configClass.isImported()) {
        registerBeanDefinitionForImportedConfigurationClass(configClass);
    }
    for (BeanMethod beanMethod : configClass.getBeanMethods()) {
        loadBeanDefinitionsForBeanMethod(beanMethod);
    }
	// 2.跳过
    loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
    // 3.对于 aopConfig对应的ConfigurationClass, 这里 getImportBeanDefinitionRegistrars()可以获取到:
    // (AspectJAutoProxyRegistrar对象, aopConfig的注解metadata)
    loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
}
private void loadBeanDefinitionsFromRegistrars(Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> registrars) {
    // 在这里, 会调用AspectJAutoProxyRegistrar的registerBeanDefinitions方法
    registrars.forEach((registrar, metadata) ->
                       registrar.registerBeanDefinitions(metadata, this.registry));
}

总结

1.我们使用ConfigurationClassPostProcessor扫描核心配置类AopConfig, 获取AopConfig的@EnableAspectJAutoProxy注解
2.递归解析注解, 找到注解中的@Import注解, @EnableAspectJAutoProxy注解的@Import标签中引用了AspectJAutoProxyRegistrar.class
3.AspectJAutoProxyRegistrar类实现了ImportBeanDefinitionRegistrar接口, 此时实例化AspectJAutoProxyRegistrar对象
4.后期调用AspectJAutoProxyRegistrar的registerBeanDefinitions方法

3.AspectJAutoProxyRegistrar 解析

3.1 AspectJAutoProxyRegistrar

上述,我们知道了AspectJAutoProxyRegistrar对象的创建,以及registerBeanDefinitions方法何时执行

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar { 
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 1.创建 AnnotationAwareAspectJAutoProxyCreator对应的 BeanDefinition, 注册到beanDefinitionMap中
        // key: org.springframework.aop.config.internalAutoProxyCreator
        // value: AnnotationAwareAspectJAutoProxyCreator对应的 BeanDefinition
        AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
        // 2.获取@EnableAspectJAutoProxy的属性: proxyTargetClass、exposeProxy(默认都为false)
        AnnotationAttributes enableAspectJAutoProxy =
            AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class); 
        // 3.默认都是false, 下面两个跳过
        if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
            AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
        }
        if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
            AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
        }
    }
}

4.AnnotationAwareAspectJAutoProxyCreator解析

  上述我们知道,在refresh()方法中的第五步方法invokeBeanFactoryPostProcessors(beanFactory)中,我们已经将@EnableAspectJAutoProxy扫描解析,创建了
@EnableAspectJAutoProxy注解中引入的@Import(AspectJAutoProxyRegistrar.class) AspectJAutoProxyRegistrar对象,同时执行了AspectJAutoProxyRegistrar对象的registerBeanDefinitions方法,向容器中注入了 AnnotationAwareAspectJAutoProxyCreator对应的 BeanDefinition
  接下来,看下AnnotationAwareAspectJAutoProxyCreator初始化, 以及如何完成aop  

4.1 AbstractApplicationContext#registerBeanPostProcessors(beanFactory)

注册拦截bean创建的BeanPostProcessor

/**
 * Instantiate and register all BeanPostProcessor beans,
 * respecting explicit order if given.
 * <p>Must be called before any instantiation of application beans.
 * 翻译: 按照顺序, 实例化并注册所有BeanPostProcessor
 * BeanPostProcessor是在普通Bean实例化之前创建并实例化完成的
 */
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
public static void registerBeanPostProcessors(
    ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
	// 1.从beanDefinitionNames中找到两个内置的BeanPostProcessor, 以及上述注册的一个, 一共三个 
    // internalAutowiredAnnotationProcessor
    // internalCommonAnnotationProcessor
    // AnnotationAwareAspectJAutoProxyCreator
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

    // 2.添加一个BeanPostProcessor: BeanPostProcessorChecker
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

    // 3.根据PriorityOrdered, Ordered, 未实现排序的分开处理
    // 实现PriorityOrdered的BeanPostProcessor
    List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    // 内置的 , 实现MergedBeanDefinitionPostProcessor的 BeanPostProcessor
    List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
    // 实现Ordered的BeanPostProcessor
    List<String> orderedPostProcessorNames = new ArrayList<>();
    // 未实现排序的BeanPostProcessor
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    // 4.遍历postProcessorNames, 有两个内置的, 且都实现了PriorityOrdered, 分别是:
    // (internalAutowiredAnnotationProcessor, AutowiredAnnotationBeanPostProcessor对应的BeanDefinition)
	// (internalCommonAnnotationProcessor, CommonAnnotationBeanPostProcessor对应的BeanDefinition)
    // AnnotationAwareAspectJAutoProxyCreator实现了Ordered接口
    // (org.springframework.aop.config.internalAutoProxyCreator, AnnotationAwareAspectJAutoProxyCreator)
    for (String ppName : postProcessorNames) {
        if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            priorityOrderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
        else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        }
        else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // First, register the BeanPostProcessors that implement PriorityOrdered.
    // 5.排序实现了PriorityOrdered的
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    // 6.把实现了PriorityOrdered的BeanPostProcessor添加到 AbstractBeanFactory中的 beanPostProcessors中,
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

    // 7.排序并注册实现Ordered接口的BeanPostProcessors
    List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
    for (String ppName : orderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        orderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, orderedPostProcessors);

    // 8.排序并注册普通的BeanPostProcessors, 这里为空, 跳过
    List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
    for (String ppName : nonOrderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        nonOrderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

    // 9.排序并注册内部BeanPostProcessors, 这里有两个, 且都为PriorityOrdered, 所在在这里重新删除又添加了一次
    sortPostProcessors(internalPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, internalPostProcessors);

    // Re-register post-processor for detecting inner beans as ApplicationListeners,
    // moving it to the end of the processor chain (for picking up proxies etc).
    // 10.再添加注册一个BeanPostProcessor 【ApplicationListenerDetector】
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

总结

1.这个方法比较简单, 根据PriorityOrdered, Ordered接口排序, 并注册排序好的BeanPostProcessor, 把BeanPostProcessor实例化后添加到 AbstractBeanFactory的beanPostProcessors中;
2.如果我们自定义了 BeanPostProcessors 也会被实例化并添加进去, 包括aop相关的 AnnotationAwareAspectJAutoProxyCreator
3.此时BeanPostProcessor的核心方法还没有执行, 他们会在普通bean的实例化前后执行

以上, @EnableAspectJAutoProxy给容器中注册一个AnnotationAwareAspectJAutoProxyCreator, AnnotationAwareAspectJAutoProxyCreator是一个BeanPostProcessor!!!

4.2 类图

spring-aop

4.3 作用

以上, AnnotationAwareAspectJAutoProxyCreator实现了BeanPostProcessor接口, 根据@Spring源码分析我们知道, 在bean的创建过程中, 我们先后使用8次BeanPostProcessor对其进行加强, 分别是:
1.第一次: 在创建bean之前, 使用【实现了InstantiationAwareBeanPostProcessor】的BeanPostProcessor来生成bean的代理对象, 如果有生成, 则直接返回
2.第二次: 如果第一次使用的过程中没有生成代理对象, 在实例化bean对象时, 使用BeanPostProcessor【SmartInstantiationAwareBeanPostProcessor】用于推断使用特殊的构造器来反射创建bean实例
3.第三次: 在实例化bean对象之后, 调用BeanPostProcessor【MergedBeanDefinitionPostProcessor】, 在@Autowired和@Resource文章解析中, 第三次使用BeanPostProcessor, 有一部分作用是寻找属性字段注入点, 将普通bean的metadata放到injectionMetadataCache缓存中的, 方便后面的属性注入
4.第四次: 如果支持循环依赖, 创建对应bean对应的ObjectFactory, 并将其放入到三级缓存中!!!用以解决循环依赖问题, 创建的ObjectFactory第四次使用BeanPostProcessor【SmartInstantiationAwareBeanPostProcessor】
5.第五、六次: 实例化完成后, 注入bean的相关属性时, 这里会第五次和第六次使用BeanPostProcessor【InstantiationAwareBeanPostProcessor】, 判断是否需要属性注入, 并完成注入
6.第七、八次: 在属性注入之后, 执行初始化方法前后, 会先后调用BeanPostProcessor, 完成AOP

以上, 在实例化bean之前, 第一次使用bdp, 生成代理对象; 如果代理对象没有生成, 在普通bean实例化时, 第二次使用bdp进行构造器推断, 实例化后第三次、第四次使用dbp, 属性注入时第五次、第六次使用bdp, 在初始化方法前后完成第七次、第八次使用bdp

接下来查看 AnnotationAwareAspectJAutoProxyCreator 如何在这八次加强分别起了什么作用:

4.3.1 第一次

第一次,使用的是InstantiationAwareBeanPostProcessor, 判断是否直接生成代理对象,AnnotationAwareAspectJAutoProxyCreator 继承了 AbstractAutoProxyCreator 类实现了 InstantiationAwareBeanPostProcessor接口,调用了其postProcessBeforeInstantiation(Class<?>, String)方法,这里以LogService为例

@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
    // 1.cacheKey == logService
    Object cacheKey = getCacheKey(beanClass, beanName);
	// 2.进入
    if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
        // 判断advisedBeans中有没有, 如果有, 直接返回 null, advisedBeans中存储的是所有需要增强的bean
        if (this.advisedBeans.containsKey(cacheKey)) {
            return null;
        }
        // 判断当前bean是否基础类型Advice、Pointcut、Advisor、AopInfrastructureBean,或是否切面(@Aspect), 跳过
        if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return null;
        }
    }

    // Create proxy here if we have a custom TargetSource.
    // Suppresses unnecessary default instantiation of the target bean:
    // The TargetSource will handle target instances in a custom fashion.
    // 3.从beanFactory中获取目标对象, 这里为null
    TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
    // 4.跳过
    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;
}
总结
这里没有生成代理对象, 走正常的bean的生命周期

4.3.2 第二次

第二次, 使用的是SmartInstantiationAwareBeanPostProcessor,用于推断实例化bean时所采用的构造器,AnnotationAwareAspectJAutoProxyCreator 继承了 AbstractAutoProxyCreator 类实现了 SmartInstantiationAwareBeanPostProcessor 接口,调用了其determineCandidateConstructors(Class<?>, String)方法,该方法返回null,其不参与构造器推断

public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) {
    return null;
}
总结
这里不参与构造器的推断

4.3.3 第三次

第三次,使用的是MergedBeanDefinitionPostProcessor,用于提前找到属性注入点,AnnotationAwareAspectJAutoProxyCreator没有直接或间接实现MergedBeanDefinitionPostProcessor接口,所以这里跳过

总结
这里跳过

4.3.4 第四次

第四次,使用的是SmartInstantiationAwareBeanPostProcessor,用于:如果在支持循环依赖的前提下,会将实例化的bean对象,创建对应的三次缓存对象singletonFactory对象,该对象的方法getEarlyBeanReference方法中第四次使用了BeanPostProcessor,用于提前暴露实例化但未初始化的bean,getEarlyBeanReference方法何时调用?

总结
用于支持循环依赖。如果a依赖b, b也依赖a, 即a和b存在相互依赖。一般情况下:
1.创建a时, 首先使用反射实例化a, 判断如果支持循环依赖, 将a的的工厂对象(重写getBean方法, 这个方法中第四次使用了PostProcessor)放入到三级缓存中
2.调用populateBean方法判断是否需要属性注入并完成属性注入, 在对a进行属性注入时, 使用AutowiredAnnotationPostProcessor, 从容器中获取b对象进行注入, 但此时容器中b并没有实例化, 这里进入到b的创建工作
3.创建b时, 首先也是使用反射实例化b, 判断如果支持循环依赖, 将b的的工厂对象(重写getBean方法, 这个方法中第四次使用了PostProcessor)放入到三级缓存中
4.调用populateBean方法判断是否需要属性注入并完成属性注入, 在对b进行属性注入时, 使用AutowiredAnnotationPostProcessor, 从容器中获取a对象进行注入, 一级缓存中获取不到, 从二级缓存中获取, 二级缓存中获取不到, 从三级缓存中获取, 三级缓存中使用a的工厂对象获取时, 会第四次使用BeanPostProcessor, 获取到a后(此时的a是刚刚实例化的a, 并没有初始化完成!), 移除三级缓存, 放入到二级缓存中。后面继续完成b的初始化
5.此时b初始化完成, 将b注入到a中, 可以继续进行a的初始化操作

4.3.5 第五次

第五次,使用的是InstantiationAwareBeanPostProcessor,用于判断bean是否需要属性注入,AnnotationAwareAspectJAutoProxyCreator 继承了 AbstractAutoProxyCreator 类实现了 InstantiationAwareBeanPostProcessor 接口,调用了其postProcessAfterInstantiation(Object, String)方法,该方法返回true,表示不会阻断属性注入

public boolean postProcessAfterInstantiation(Object bean, String beanName) {
    return true;
}
总结
这里不会阻断属性注入,即不会影响属性注入

4.3.6 第六次

第六次,使用的是InstantiationAwareBeanPostProcessor,用于bean的属性注入,AnnotationAwareAspectJAutoProxyCreator 继承了 AbstractAutoProxyCreator 类实现了 InstantiationAwareBeanPostProcessor 接口,调用了其postProcessProperties(PropertyValues, Object, String)方法,该方法没有作任何处理

@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
    return pvs;
}
总结
这里是空实现, 不会参与属性注入

4.3.7 第七次

第七次,使用的是BeanPostProcessor,在bean属性注入之后,执行初始化方法之前,对bean进行aop操作,AnnotationAwareAspectJAutoProxyCreator 继承了 AbstractAutoProxyCreator 类实现了 BeanPostProcessor 接口,调用了其 postProcessBeforeInitialization(Object, String)方法,该方法没有作任何处理

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
    return bean;
}
总结
这里是空实现, 不参与bean的初始化方法之前的aop

4.3.8 第八次

第八次,使用的是BeanPostProcessor,在执行初始化方法之后,对bean进行aop操作,AnnotationAwareAspectJAutoProxyCreator 继承了 AbstractAutoProxyCreator 类实现了 BeanPostProcessor 接口,调用了其 postProcessBeforeInitialization(Object, String)方法,生成代理对象

@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
    if (bean != null) {
        // 1.cacheKey == "logService"
        Object cacheKey = getCacheKey(bean.getClass(), beanName);
        // 2.earlyProxyReferences中不包含logService, 所以这里为true, 进入
        if (this.earlyProxyReferences.remove(cacheKey) != bean) {
            // 3.生成代理对象
            return wrapIfNecessary(bean, beanName, cacheKey);
        }
    }
    return bean;
}

AbstractAutoProxyCreator#wrapIfNecessary(Object bean, String beanName, Object cacheKey)

/* 生成代理对象
 * bean --> logSerivice
 * beanName --> logService
 * cacheKey --> logService(String)
 */
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    // 1.这里 targetSourcedBeans 不包含 logService, 跳过
    if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
        return bean;
    }
    // 2.这里 advisedBeans 中不包含 logService, 跳过
    if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
        return bean;
    }
    // 3.下面两个条件都不满足, 为false, 跳过
    if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }

    // Create proxy if we have advice.
    // 4.获取增强器, 这里获取2个
    // 1.内置的, org.springframework.aop.interceptor.ExposeInvocationInterceptor.ADVISOR
    // 2.LogAspect中@Before对应的方法的Advisor
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    if (specificInterceptors != DO_NOT_PROXY) {
        // 5.将(logService, True)存储到 advisedBeans
        this.advisedBeans.put(cacheKey, Boolean.TRUE);
        // 6.创建代理对象
        Object proxy = createProxy(
            bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
        // 7.将(logService, 和代理对象对应的Class)存储到 proxyTypes
        this.proxyTypes.put(cacheKey, proxy.getClass());
        // 8.返回代理对象
        return proxy;
    }
    // 9.这里跳过
    this.advisedBeans.put(cacheKey, Boolean.FALSE);
    return bean;
}

AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, @Nullable TargetSource targetSource)

/**
 * 获取增强器
 */
protected Object[] getAdvicesAndAdvisorsForBean(
Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
	// 见下, 这里获取2个
    // 1.内置的, org.springframework.aop.interceptor.ExposeInvocationInterceptor.ADVISOR
    // 2.LogAspect中@Before对应的方法的Advisor
    List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
    if (advisors.isEmpty()) {
    	return DO_NOT_PROXY;
    }
    return advisors.toArray();
}

AbstractAdvisorAutoProxyCreator#findEligibleAdvisors(Class<?> beanClass, String beanName)

protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
    // 1.获取所有增强器
    // 找到候选的增强器, 其实就是寻找有@Aspect注解的类, 把所有@Aspect的类找到, 封装成Advisor对象
    // 这里只有一个, LogAspect中@Before对应的方法的Advisor
    List<Advisor> candidateAdvisors = findCandidateAdvisors();
    // 2.获取可用增强器, 这里还是只有1个, LogAspect中@Before对应的方法的Advisor
    List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
    // 3.这里又添加一个内置的: org.springframework.aop.interceptor.ExposeInvocationInterceptor.ADVISOR
    extendAdvisors(eligibleAdvisors);
    if (!eligibleAdvisors.isEmpty()) {
        eligibleAdvisors = sortAdvisors(eligibleAdvisors);
    }
    return eligibleAdvisors;
}

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) {
        // 2.进入, 见下
        advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
    }
    return advisors;
}

BeanFactoryAspectJAdvisorsBuilder.buildAspectJAdvisors()

/**
	 * Look for AspectJ-annotated aspect beans in the current bean factory,
	 * and return to a list of Spring AOP Advisors representing them.
	 * <p>Creates a Spring Advisor for each AspectJ advice method.
	 * @return the list of {@link org.springframework.aop.Advisor} beans
	 * @see #isEligibleBean
	 */
public List<Advisor> buildAspectJAdvisors() {
    // 1.这里已经拿到过了, 为logAspect, 但是创建第一个bean, aopConfig时这里是为空的
    List<String> aspectNames = this.aspectBeanNames;
	// 2.为空时, 第一次创建, 这里是在创建aopConfig时
    if (aspectNames == null) {
        synchronized (this) {
            aspectNames = this.aspectBeanNames;
            if (aspectNames == null) {
                List<Advisor> advisors = new ArrayList<>();
                aspectNames = new ArrayList<>();
                // 3.获取容器中目前所有的bean或beanDefinition对应beanName
                String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                    this.beanFactory, Object.class, true, false);
                for (String beanName : beanNames) {
                    // 4.是否为eligibleBean
                    if (!isEligibleBean(beanName)) {
                        continue;
                    }
                    // We must be careful not to instantiate beans eagerly as in this case they
                    // would be cached by the Spring container but would not have been weaved.
                    // 5.获取bean的Class对象
                    Class<?> beanType = this.beanFactory.getType(beanName);
                    if (beanType == null) {
                        continue;
                    }
                    // 6.判断是否有@Aspect注解, 这里只有LogAspect有
                    if (this.advisorFactory.isAspect(beanType)) {
                        // 7.添加到aspectNames中, 缓存起来
                        aspectNames.add(beanName);
                        // 8.封装AspectMetadata对象
                        AspectMetadata amd = new AspectMetadata(beanType, beanName);
                        if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
                            // 9.封装 MetadataAwareAspectInstanceFactory对象
                            MetadataAwareAspectInstanceFactory factory =
                                new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
                            // 10.创建切面对象 Advisor, 见下, 这里返回的是有@Aspect标签的类中的切面方法(有@Before标签 @After标签等)所对应的Adviso
                            List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
                            if (this.beanFactory.isSingleton(beanName)) {
                                // 11.放入缓存(logAspect, @Before方法对应的Advisor)
                                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;
            }
        }
    }
	// 12.后面的bean创建时, 再获取切面Advisor时, 根据aspectName获取对应的List<Advisor>
    if (aspectNames.isEmpty()) {
        return Collections.emptyList();
    }
    List<Advisor> advisors = new ArrayList<>();
    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;
}

ReflectiveAspectJAdvisorFactory#getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory)

@Override
public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
    // 1.获取有@Aspect注解的Class对象 --> LogAspect
    Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
    // 2.aspectName --> logAspect
    String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
    // 3.校验, 跳过
    validate(aspectClass);

    // We need to wrap the MetadataAwareAspectInstanceFactory with a decorator
    // so that it will only instantiate once.
    // 4.封装MetadataAwareAspectInstanceFactory, 使得LogAspect只会被初始化一次
    MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =
        new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);

    List<Advisor> advisors = new ArrayList<>();
    // 5.获取没有@PointCut注解的方法, 所以一般方法、父类方法以及@Before、@After等切面方法都会被获取到
    for (Method method : getAdvisorMethods(aspectClass)) {
        // 6.遍历这些方法, 封装成Advisor对象, 这里只有@Before、 @After这些切面方法才会被封装成Advisor, 其他为null
        Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);
        if (advisor != null) {
            advisors.add(advisor);
        }
    }

    // If it's a per target aspect, emit the dummy instantiating aspect.
    // 7.上面获取的advisors中只有一个, 即@Before对应的方法 logBefore
    // 8.这里跳过
    if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
        Advisor instantiationAdvisor = new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);
        advisors.add(0, instantiationAdvisor);
    }

    // Find introduction fields.
    // 9.这里跳过
    for (Field field : aspectClass.getDeclaredFields()) {
        Advisor advisor = getDeclareParentsAdvisor(field);
        if (advisor != null) {
            advisors.add(advisor);
        }
    }
	// 10.返回List<Advisor>
    return advisors;
}

AbstractAutoProxyCreator#(Class<?> beanClass, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource)

/**
 * Create an AOP proxy for the given bean.
 * @param beanClass the class of the bean
 * @param beanName the name of the bean
 * @param specificInterceptors the set of interceptors that is
 * specific to this bean (may be empty, but not null)
 * @param targetSource the TargetSource for the proxy,
 * already pre-configured to access the bean
 * @return the AOP proxy for the bean
 * @see #buildAdvisors
 */
protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
                             @Nullable Object[] specificInterceptors, TargetSource targetSource) {
	// 1.进入, 设置属性
    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        // "org.springframework.aop.framework.autoproxy.AutoProxyUtils.originalTargetClass" --> targetClass(即LogService对应的Class)
        AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
    }
    // 2.创建ProxyFactory
    ProxyFactory proxyFactory = new ProxyFactory();
    // 3.拷贝属性值
    // proxyTargetClass(false), optimize(false), exposeProxy(false), frozen(false), opaque(false)
    proxyFactory.copyFrom(this);
	// proxyTargetClass: 为true时表示使用cglib动态代理
    if (!proxyFactory.isProxyTargetClass()) {
        // 判断bd的org.springframework.aop.framework.autoproxy.AutoProxyUtils.preserveTargetClass属性是否为true, 默认为null
        if (shouldProxyTargetClass(beanClass, beanName)) {
            proxyFactory.setProxyTargetClass(true);
        }
        else {
            // 找到targetClass实现的接口, 当没有实现接口时, 修改proxyTargetClass属性为true, 即表示使用cglib动态代理
            evaluateProxyInterfaces(beanClass, proxyFactory);
        }
    }
	// 4.获取增强器, 这里有两个, 一个内置的, 一个LogAspect中的@Before
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    proxyFactory.addAdvisors(advisors);
    proxyFactory.setTargetSource(targetSource);
    customizeProxyFactory(proxyFactory);

    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }
    // 5.getProxyClassLoader(), 这里获取的是AppClassLoader
    return proxyFactory.getProxy(getProxyClassLoader());
}

ProxyFactory#getProxy(@Nullable ClassLoader classLoader)

/**
 * Create a new proxy according to the settings in this factory.
 * <p>Can be called repeatedly. Effect will vary if we've added
 * or removed interfaces. Can add and remove interceptors.
 * <p>Uses the given class loader (if necessary for proxy creation).
 * @param classLoader the class loader to create the proxy with
 * (or {@code null} for the low-level proxy facility's default)
 * @return the proxy object
 */
public Object getProxy(@Nullable ClassLoader classLoader) {
    // 生成代理对象
    return createAopProxy().getProxy(classLoader);
}

ProxyCreatorSupport#createAopProxy()

protected final synchronized AopProxy createAopProxy() {
    if (!this.active) {
        activate();
    }
    // 这里getAopProxyFactory() --> DefaultAopProxyFactory
    return getAopProxyFactory().createAopProxy(this);
}

DefaultAopProxyFactory#createAopProxy(AdvisedSupport config)

@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    // 判断 optimize属性、proxyTargetClass属性以及 是否没有实现接口
    if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
        Class<?> targetClass = config.getTargetClass();
        if (targetClass == null) {
            throw new AopConfigException("TargetSource cannot determine target class: " +
    "Either an interface or a target is required for proxy creation.");
        }
        if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
            return new JdkDynamicAopProxy(config);
        }
        // 使用cglib
        return new ObjenesisCglibAopProxy(config);
    }
    else {
        // 使用jdk
        return new JdkDynamicAopProxy(config);
    }
}
总结
1.判断是否需要进行代理
2.获取当前bean的所有增强器(通知方法), 找到能在当前bean使用的增强器(找到哪些通知方法需要切入到当前bean), 并排序
3.如果当前bean需要增强, 创建当前bean的代理对象:
  获取所有增强器(通知方法), 保存到ProxyFactory中, 使用JdkDynamicAopProxy或者ObjenesisCglibAopProxy创建代理对象

5.方法执行

5.1 准备

修改LogAspect(先不考虑@Around)

@Component
@Aspect
@Slf4j
public class LogAspect {

    private static final String POINT_CUT =
        "execution(public void com.tca.spring.framework.learning.aop.service.LogService.*(..))";

    @Pointcut(value = POINT_CUT)
    private void pointCut() {}


    @Before(value = "pointCut()")
    public void logBefore(JoinPoint joinPoint) {
        log.info("logBefore 执行");
    }

    @After(value = "pointCut()")
    public void logAfter(JoinPoint joinPoint) {
        log.info("logAfter 执行");
    }


    @AfterReturning(value = "pointCut()")
    public void afterReturning() {
        log.info("afterReturning 执行");
    }

    @AfterThrowing(value = "pointCut()")
    public void afterThrowing() {
        log.info("afterThrowing 执行");
    }

}

启动类

public class AopStarter {

    public static void main(String[] args) {
        ApplicationContext ac = new AnnotationConfigApplicationContext(AopConfig.class);
        LogService logService = ac.getBean(LogService.class);
        // 容器中保存了logService的代理对象(jdkproxy或cglib代理), 这个对象里面保存了详细信息(比如增强器, 目标对象)
        logService.log("Messi", "welcome");
    }
}

5.2 获取拦截器

调用logService#log方法进入到CglibAopProxy#intercept方法

@Override
@Nullable
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
    Object oldProxy = null;
    boolean setProxyContext = false;
    Object target = null;
    TargetSource targetSource = this.advised.getTargetSource();
    try {
        if (this.advised.exposeProxy) {
            // Make invocation available if necessary.
            oldProxy = AopContext.setCurrentProxy(proxy);
            setProxyContext = true;
        }
        // Get as late as possible to minimize the time we "own" the target, in case it comes from a pool...
        target = targetSource.getTarget();
        Class<?> targetClass = (target != null ? target.getClass() : null);
        // 1.获取目标方法的拦截器链!
        List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
        Object retVal;
        // Check whether we only have one InvokerInterceptor: that is,
        // no real advice, but just reflective invocation of the target.
        if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
            // We can skip creating a MethodInvocation: just invoke the target directly.
            // Note that the final invoker must be an InvokerInterceptor, so we know
            // it does nothing but a reflective operation on the target, and no hot
            // swapping or fancy proxying.
            // 2.如果没有拦截器链, 直接执行目标方法
            Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
            retVal = methodProxy.invoke(target, argsToUse);
        }
        else {
            // We need to create a method invocation...
            // 3.如果有拦截器链, 创建CglibMethodInvocation对象, 并执行, 见@5.3 方法执行
            retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
        }
        retVal = processReturnType(proxy, target, method, retVal);
        return retVal;
    }
    finally {
        if (target != null && !targetSource.isStatic()) {
            targetSource.releaseTarget(target);
        }
        if (setProxyContext) {
            // Restore old proxy.
            AopContext.setCurrentProxy(oldProxy);
        }
    }
}

AdvisedSupport#getInterceptorsAndDynamicInterceptionAdvice

/**
	 * Determine a list of {@link org.aopalliance.intercept.MethodInterceptor} objects
	 * for the given method, based on this configuration.
	 * @param method the proxied method
	 * @param targetClass the target class
	 * @return a List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers)
	 */
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
    MethodCacheKey cacheKey = new MethodCacheKey(method);
    List<Object> cached = this.methodCache.get(cacheKey);
    if (cached == null) {
        cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
            this, method, targetClass);
        this.methodCache.put(cacheKey, cached);
    }
    return cached;
}

DefaultAdvisorChainFactory#getInterceptorsAndDynamicInterceptionAdvice

@Override
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
    Advised config, Method method, @Nullable Class<?> targetClass) {

    // This is somewhat tricky... We have to process introductions first,
    // but we need to preserve order in the ultimate list.
    AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
    Advisor[] advisors = config.getAdvisors();
    List<Object> interceptorList = new ArrayList<>(advisors.length);
    Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
    Boolean hasIntroductions = null;

    // 遍历所有增强器, 将增强器转换成interceptor拦截器
    for (Advisor advisor : advisors) {
        if (advisor instanceof PointcutAdvisor) {
            // Add it conditionally.
            PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
            if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
                MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
                boolean match;
                if (mm instanceof IntroductionAwareMethodMatcher) {
                    if (hasIntroductions == null) {
                        hasIntroductions = hasMatchingIntroductions(advisors, actualClass);
                    }
                    match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);
                }
                else {
                    match = mm.matches(method, actualClass);
                }
                if (match) {
                    MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
                    if (mm.isRuntime()) {
                        // Creating a new object instance in the getInterceptors() method
                        // isn't a problem as we normally cache created chains.
                        for (MethodInterceptor interceptor : interceptors) {
                            interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
                        }
                    }
                    else {
                        interceptorList.addAll(Arrays.asList(interceptors));
                    }
                }
            }
        }
        else if (advisor instanceof IntroductionAdvisor) {
            IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
            if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
                Interceptor[] interceptors = registry.getInterceptors(advisor);
                interceptorList.addAll(Arrays.asList(interceptors));
            }
        }
        else {
            Interceptor[] interceptors = registry.getInterceptors(advisor);
            interceptorList.addAll(Arrays.asList(interceptors));
        }
    }

    return interceptorList;
}

5.3 方法执行

方法执行的过程就是拦截器执行的过程

ReflectiveMethodInvocation#proceed()

public Object proceed() throws Throwable {
    // We start with an index of -1 and increment early.
    // 当执行到最后一个拦截器时, 进入
    if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
        return invokeJoinpoint();
    }
	// 获取下一个拦截器
    Object interceptorOrInterceptionAdvice =
        this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
    if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
        // Evaluate dynamic method matcher here: static part will already have
        // been evaluated and found to match.
        InterceptorAndDynamicMethodMatcher dm =
            (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
        Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
        if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
            return dm.interceptor.invoke(this);
        }
        else {
            // Dynamic matching failed.
            // Skip this interceptor and invoke the next in the chain.
            return proceed();
        }
    }
    else {
        // It's an interceptor, so we just invoke it: The pointcut will have
        // been evaluated statically before this object was constructed.
        return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
    }
}

第一次拦截

第一次获取的拦截器是ExposeInvocationInterceptor(这个是默认添加的拦截器), 它不是InterceptorAndDynamicMethodMatcher, 执行它的invoke(this)方法, 它在invoke(this)方法中继续调用proceed方法,
拿到第二个拦截器, 为AspectJAfterThrowingAdvice

ExposeInvocationInterceptor#invoke(MethodInvocation mi)

@Override
public Object invoke(MethodInvocation mi) throws Throwable {
    MethodInvocation oldInvocation = invocation.get();
    // 具体作用, 待分析
    invocation.set(mi);
    try {
        // 继续调用mi.invoke
        return mi.proceed();
    }
    finally {
        invocation.set(oldInvocation);
    }
}

第二次拦截

由上面可知, 执行第一个拦截器时, 继续执行mi.invoke(), 获取第二个拦截器, 为AspectJAfterThrowingAdvice, 它不是InterceptorAndDynamicMethodMatcher, 执行它的invoke(this)方法, 它在invoke(this)方法中继续调用proceed方法, 拿到第三个拦截器, 为AfterReturingAdviceInteceptor, 但是这里会捕获第三个拦截器执行的异常, 并判断当前异常是否会触发其@AfterThrowing的方法, 并执行

AspectJAfterThrowingAdvice#invoke(MethodInvocation mi)

@Override
public Object invoke(MethodInvocation mi) throws Throwable {
    try {
        return mi.proceed();
    }
    catch (Throwable ex) {
        if (shouldInvokeOnThrowing(ex)) {
            invokeAdviceMethod(getJoinPointMatch(), null, ex);
        }
        throw ex;
    }
}

第三次拦截

由上面可知, 执行第二个拦截器时, 会继续执行mi.invoke(), 获取第三个拦截器, 为AfterReturningAdviceInterceptor, 它不是InterceptorAndDynamicMethodMatcher, 执行它的invoke(this)方法,
执行invoke方法时, 会先继续调用proceed方法, 去拿第四个拦截器并执行, 执行完成之后, 会触发@AfterReturning的方法

AfterReturningAdviceInterceptor#invoke(MethodInvocation mi)

@Override
public Object invoke(MethodInvocation mi) throws Throwable {
    Object retVal = mi.proceed();
    this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
    return retVal;
}

第四次拦截

由上面可知, 执行第三个拦截器时, 会继续执行mi.invoke(), 获取第四个拦截器, 为AspectJAfterAdvice, 它不是InterceptorAndDynamicMethodMatcher, 执行它的invoke(this)方法, 执行invoke方法时, 会继续调用proceed方法, 去拿第五个拦截器并执行, 执行完之后, 会在finally中触发@After方法

AspectJAfterAdvice#invoke(MethodInvocation mi)

@Override
public Object invoke(MethodInvocation mi) throws Throwable {
    try {
        return mi.proceed();
    }
    finally {
        invokeAdviceMethod(getJoinPointMatch(), null, null);
    }
}

第五次拦截

由上面可知, 执行第四个拦截器时, 会继续执行mi.invoke(), 获取第五个拦截器, 为MethodBeforeAdviceInterceptor, 它不是InterceptorAndDynamicMethodMatcher, 执行它的invoke(this)方法, 执行invoke方法时, 会先调用@Before方法, 后面继续调用proceed方法, 此时:
this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() 为true, 执行invokeJoinpoint()方法, 这个方法中会调用目标类的目标方法

MethodBeforeAdviceInterceptor#invoke(MethodInvocation mi)

@Override
public Object invoke(MethodInvocation mi) throws Throwable {
    this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
    return mi.proceed();
}

总结

综上, 
在第五个拦截器中执行了@Before方法和目标类的目标方法, 此时第五个拦截器执行完毕, 并返回到了第四个拦截器中的invoke方法;
第四个拦截器执行finally代码块, 执行@After方法, 此时第四个拦截器执行完毕, 并返回到第三个拦截器中的invoke方法;
第三个拦截器执行@AfterReturning方法, 返回执行结果, 此时此三个拦截器执行完成, 并返回到第二个拦截器中的invoke方法;
第二个拦截器没有捕获到异常, 所以将第三个拦截器的返回结果直接返回出去, 第二个拦截器执行完成, 并返回到第一个拦截器的invoke方法;
第一个拦截器, 拿到返回结果, 执行finally代码块之后返回结果