Spring源码分析~AOP如何生成代理对象

注意:各个版本可能有些不一致,我看的版本:4.3.17

看源码肯定需要一个入口,我们准备了一个demo,很简单,一个main方法,一个config类,一个对象(需要被代理的对象),一个日志切面类;

一个对象:

package com.anotation.aop;

import org.springframework.stereotype.Service;

@Service
public class MathCalculator {
	
	public int divide(int i,int j){
		System.out.println("MathCalculator...div...");
		return i/j;	
	}
}

切面类:用于给上面的对象增强日志功能

package com.anotation.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * 切面类 @Aspect
 */
@Aspect
@Service
public class LogAspects {

	@Pointcut("execution(public int com.anotation.aop.MathCalculator.*(..))")
	public void pointCut(){};

	@Before("pointCut()")
	public void logStart(JoinPoint joinPoint){
		Object[] args = joinPoint.getArgs();
		System.out.println(""+joinPoint.getSignature().getName()+"方法运行,@Before:{"+Arrays.asList(args)+"}");
	}
	
	@After("com.anotation.aop.LogAspects.pointCut()")
	public void logEnd(JoinPoint joinPoint){
		System.out.println(""+joinPoint.getSignature().getName()+"方法运行,@After");
	}
	
	@AfterReturning(value="pointCut()",returning="result")
	public void logReturn(JoinPoint joinPoint,Object result){
		System.out.println(""+joinPoint.getSignature().getName()+"@AfterReturning:"+"{"+result+"}");
	}

	//JoinPoint一定要出现在参数的第一位
	@AfterThrowing(value="pointCut()",throwing="exception")
	public void logException(JoinPoint joinPoint,Exception exception){
		System.out.println(""+joinPoint.getSignature().getName()+"方法运行产生异常,@AfterThrowing:"+"{"+exception+"}");
	}

}

config类:

package com.anotation.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@EnableAspectJAutoProxy
@Configuration
@ComponentScan(value = "com.anotation.aop")
public class MainConfigOfAOP {

}

重点看@EnableAspectJAutoProxy的作用,它是一个注解,主要作用是引入:@Import(AspectJAutoProxyRegistrar.class)

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
	boolean proxyTargetClass() default false;
	boolean exposeProxy() default false;
}

而AspectJAutoProxyRegistrar.java的作用主要是注册:AnnotationAwareAspectJAutoProxyCreator.java,这个类是一个后置处理器BeanPostProcessor,这个AnnotationAwareAspectJAutoProxyCreator是实现aop功能的核心,因为他会在它的方法postProcessAfterInitialization()中对目标对象进行增强(实现AOP),后面会细说。

main函数:

package com.atguigu.test;

import com.anotation.aop.MathCalculator;
import com.anotation.config.MainConfigOfAOP;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class IOCTest_AOP {
	@Test
	public void test01() throws InterruptedException {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfAOP.class);
		MathCalculator mathCalculator = applicationContext.getBean(MathCalculator.class);
		mathCalculator.divide(4, 2);
		Thread.sleep(2000);
		applicationContext.close();
	}
}

先看运行结果:

divide方法运行,@Before:{[4, 2]}
MathCalculator...div...
divide方法运行,@After
divide@AfterReturning:{2}

可以看到,增强已经生效,下面现在开始分析源码;分析MathCalculator是何时被增强的(生成代理对象),因为MathCalculator没有实现接口,那它应该无法用jdk动态代理来实现,而必须用CGLIB来实现?源码会解释一切。

先看第一行:new AnnotationConfigApplicationContext(MainConfigOfAOP.class),这是一个构建方法,代码如下:

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
	this();
	register(annotatedClasses);
	refresh();
}

重度看refresh()方法里面的操作;

@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        try {
            // Instantiate all remaining (non-lazy-init) singletons.
            finishBeanFactoryInitialization(beanFactory);
        }
    }
}

我们要看的MathCalculator是如何被增强处理的,看主要代码finishBeanFactoryInitialization(beanFactory)中,进入方法:

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    // Initialize conversion service for this context.
    if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
            beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
        beanFactory.setConversionService(
                beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
    }

    // Register a default embedded value resolver if no bean post-processor
    // (such as a PropertyPlaceholderConfigurer bean) registered any before:
    // at this point, primarily for resolution in annotation attribute values.
    if (!beanFactory.hasEmbeddedValueResolver()) {
        beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
            @Override
            public String resolveStringValue(String strVal) {
                return getEnvironment().resolvePlaceholders(strVal);
            }
        });
    }

    // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
        getBean(weaverAwareName);
    }

    // Stop using the temporary ClassLoader for type matching.
    beanFactory.setTempClassLoader(null);

    // Allow for caching all bean definition metadata, not expecting further changes.
    beanFactory.freezeConfiguration();

    // Instantiate all remaining (non-lazy-init) singletons.
    beanFactory.preInstantiateSingletons();
}

我们要看的在最后一行:beanFactory.preInstantiateSingletons(),该beanFactory是DefaultListableBeanFactory,继续进入preInstantiateSingletons方法:

@Override
public void preInstantiateSingletons() throws BeansException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Pre-instantiating singletons in " + this);
    }

    // Iterate over a copy to allow for init methods which in turn register new bean definitions.
    // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
    List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);

    // Trigger initialization of all non-lazy singleton beans...
    for (String beanName : beanNames) {
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            if (isFactoryBean(beanName)) {
                final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
                boolean isEagerInit;
                if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                    isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
                        @Override
                        public Boolean run() {
                            return ((SmartFactoryBean<?>) factory).isEagerInit();
                        }
                    }, getAccessControlContext());
                }
                else {
                    isEagerInit = (factory instanceof SmartFactoryBean &&
                            ((SmartFactoryBean<?>) factory).isEagerInit());
                }
                if (isEagerInit) {
                    getBean(beanName);
                }
            }
            else {
                getBean(beanName);
            }
        }
    }

    // Trigger post-initialization callback for all applicable beans...
    for (String beanName : beanNames) {
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) {
            final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    @Override
                    public Object run() {
                        smartSingleton.afterSingletonsInstantiated();
                        return null;
                    }
                }, getAccessControlContext());
            }
            else {
                smartSingleton.afterSingletonsInstantiated();
            }
        }
    }
}

我们要的在这个方法里面的getBean(beanName);一直根据会到:AbstractBeanFactory.getBean(String beanName)这个方法里面:这个方法调用类内部的AbstractBeanFactory.doGetBean方法:

protected <T> T doGetBean(
        final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
        throws BeansException {

    final String beanName = transformedBeanName(name);
    Object bean;

    // Eagerly check singleton cache for manually registered singletons.
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
        if (logger.isDebugEnabled()) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
                        "' that is not fully initialized yet - a consequence of a circular reference");
            }
            else {
                logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    else {
        // Fail if we're already creating this bean instance:
        // We're assumably within a circular reference.
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }

        // Check if bean definition exists in this factory.
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            // Not found -> check parent.
            String nameToLookup = originalBeanName(name);
            if (args != null) {
                // Delegation to parent with explicit args.
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            }
            else {
                // No args -> delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
        }

        if (!typeCheckOnly) {
            markBeanAsCreated(beanName);
        }

        try {
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);

            // Guarantee initialization of beans that the current bean depends on.
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    if (isDependent(beanName, dep)) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                    }
                    registerDependentBean(dep, beanName);
                    try {
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }

            // Create bean instance.
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
                    @Override
                    public Object getObject() throws BeansException {
                        try {
                            return createBean(beanName, mbd, args);
                        }
                        catch (BeansException ex) {
                            // Explicitly remove instance from singleton cache: It might have been put there
                            // eagerly by the creation process, to allow for circular reference resolution.
                            // Also remove any beans that received a temporary reference to the bean.
                            destroySingleton(beanName);
                            throw ex;
                        }
                    }
                });
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            }

            else if (mbd.isPrototype()) {
                // It's a prototype -> create a new instance.
                Object prototypeInstance = null;
                try {
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            }

            else {
                String scopeName = mbd.getScope();
                final Scope scope = this.scopes.get(scopeName);
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                }
                try {
                    Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
                        @Override
                        public Object getObject() throws BeansException {
                            beforePrototypeCreation(beanName);
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            finally {
                                afterPrototypeCreation(beanName);
                            }
                        }
                    });
                    bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                }
                catch (IllegalStateException ex) {
                    throw new BeanCreationException(beanName,
                            "Scope '" + scopeName + "' is not active for the current thread; consider " +
                                    "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                            ex);
                }
            }
        }
        catch (BeansException ex) {
            cleanupAfterBeanCreationFailure(beanName);
            throw ex;
        }
    }

    // Check if required type matches the type of the actual bean instance.
    if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
        try {
            return getTypeConverter().convertIfNecessary(bean, requiredType);
        }
        catch (TypeMismatchException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to convert bean '" + name + "' to required type '" +
                        ClassUtils.getQualifiedName(requiredType) + "'", ex);
            }
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
    }
    return (T) bean;
}

这个代码很长,我们只看我们要的核心:下面这一段代码:

// Create bean instance.
if (mbd.isSingleton()) {
    sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
        @Override
        public Object getObject() throws BeansException {
            try {
                return createBean(beanName, mbd, args);
            }
            catch (BeansException ex) {
                // Explicitly remove instance from singleton cache: It might have been put there
                // eagerly by the creation process, to allow for circular reference resolution.
                // Also remove any beans that received a temporary reference to the bean.
                destroySingleton(beanName);
                throw ex;
            }
        }
    });
    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

看里面的return createBean(beanName, mbd, args),调用的是:AbstractAutowireCapableBeanFactory.createBean这个方法:

@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating instance of bean '" + beanName + "'");
    }
    RootBeanDefinition mbdToUse = mbd;

    // Make sure bean class is actually resolved at this point, and
    // clone the bean definition in case of a dynamically resolved Class
    // which cannot be stored in the shared merged bean definition.
    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    }

    // Prepare method overrides.
    try {
        mbdToUse.prepareMethodOverrides();
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                beanName, "Validation of method overrides failed", ex);
    }

    try {
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) {
            return bean;
        }
    }
    catch (Throwable ex) {
        throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                "BeanPostProcessor before instantiation of bean failed", ex);
    }

    Object beanInstance = doCreateBean(beanName, mbdToUse, args);
    if (logger.isDebugEnabled()) {
        logger.debug("Finished creating instance of bean '" + beanName + "'");
    }
    return beanInstance;
}

我们要的在Object beanInstance = doCreateBean(beanName, mbdToUse, args)这一行里面:doCreateBean很长,我们重点看如下几行:

// Initialize the bean instance.
Object exposedObject = bean;
    try {
    populateBean(beanName, mbd, instanceWrapper);
    if (exposedObject != null) {
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
}

重点看exposedObject = initializeBean(beanName, exposedObject, mbd)这行代码,跟进去:

AbstractAutowireCapableBeanFactory.initializeBean():

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                invokeAwareMethods(beanName, bean);
                return null;
            }
        }, getAccessControlContext());
    }
    else {
        invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    try {
        invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                (mbd != null ? mbd.getResourceDescription() : null),
                beanName, "Invocation of init method failed", ex);
    }
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }
    return wrappedBean;
}

重点看这一行:wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName),进入这个方法:

AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization():

@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
        throws BeansException {

    Object result = existingBean;
    for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
        result = beanProcessor.postProcessAfterInitialization(result, beanName);
        if (result == null) {
            return result;
        }
    }
    return result;
}

我们已经能看到后置处理器的遍历了,在getBeanPostProcessors()会有一个后置处理器叫做:AnnotationAwareAspectJAutoProxyCreator,执行其postProcessAfterInitialization方法,实际是执行其父类的AbstractAutoProxyCreator.postProcessAfterInitialization()方法:父类postProcessAfterInitialization如下:

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean != null) {
        Object cacheKey = getCacheKey(bean.getClass(), beanName);
        if (!this.earlyProxyReferences.contains(cacheKey)) {
            return wrapIfNecessary(bean, beanName, cacheKey);
        }
    }
    return bean;
}

return wrapIfNecessary(bean, beanName, cacheKey)这行,AbstractAutoProxyCreator.wrapIfNecessary();

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    if (beanName != null && 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;
    }

    // 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);
    return bean;
}

这个方法里面的return的bean已经是我们要的代理对象了(aop增强的对象了);现在好办了,看如何生成的:看这行:

Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
createProxy方法实现如下:
protected Object createProxy(
        Class<?> beanClass, String beanName, 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()) {
        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());
}

先看这几行:

if (!proxyFactory.isProxyTargetClass()) {
    if (shouldProxyTargetClass(beanClass, beanName)) {
        proxyFactory.setProxyTargetClass(true);
    }
    else {
        evaluateProxyInterfaces(beanClass, proxyFactory);
    }
}

用于判断被代理类是否实现了接口,即能否用jdk动态代理进行增强;再看下面几行:

Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
proxyFactory.addAdvisors(advisors);
proxyFactory.setTargetSource(targetSource);
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
    proxyFactory.setPreFiltered(true);
}

这几行是获取需要哪些增强,即advice;

最后一行

proxyFactory.getProxy(getProxyClassLoader());

根据上面的判断决定使用CGLIB还是JDK动态代理来创建代理对象;默认的两个实现:

CglibAopProxy.java和JdkDynamicAopProxy.java

大体流程已经论述完了,可能你有很多疑惑,这个需要不断的debug去调试才能搞得明白,Spring源码读起来还是有点难度的,我目前其实也是一知半解,读者见谅~我这里只讲了关于如何生成代理对象的逻辑,而关于BeanPostProcessor相关的加载都没有详细说明,待我自己搞清楚了再详细写~

来个总结:

/**
 * 说明:
 *   @EnableAspectJAutoProxy,开启基于注解的aop模式
 *
 *
 *   AOP原理:看给容器中注册了什么组件,这个组件什么时候工作,这个组件的功能
 *      @EnableAspectJAutoProxy注解:
 *    1、@EnableAspectJAutoProxy
 *    @Import(AspectJAutoProxyRegistrar.class):给容器中导入AspectJAutoProxyRegistrar:
 *       AspectJAutoProxyRegistrar他给容器注册一个AnnotationAwareAspectJAutoProxyCreator
 *
 *    AnnotationAwareAspectJAutoProxyCreator
 * 		AnnotationAwareAspectJAutoProxyCreator
 * 			->AspectJAwareAdvisorAutoProxyCreator
 * 				->AbstractAdvisorAutoProxyCreator
 * 					->AbstractAutoProxyCreator
 * 							implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware
 * 						关注后置处理器(在bean初始化完成前后做的事情)、自动装配BeanFactoryAware
 *
 *
 * 	  AbstractAutoProxyCreator.setBeanFactory()
 *
 *    AbstractAutoProxyCreator.有后置处理器的逻辑
 *
 *    AbstractAdvisorAutoProxyCreator.setBeanFactory()->initBeanFactory()
 *
 *    AnnotationAwareAspectJAutoProxyCreator.initBeanFactory()
 *
 * 流程
 *    1、传入配置类,创建ioc容器
 *    2、注册配置类,调用refresh()方法,刷新容器
 *    3、registerBeanPostProcessors(beanFactory);注册bean的后置处理器来方便拦截bean的创建
 *       1) 先获取ioc容器已经定义了的需要创建对象的所有BeanPostProcessor
 *       2) 给容器中加别的BeanPostProcessor
 *       3)优先注册实现了PriorityOrdered接口的BeanPostProcessor
 *       4)再给容器中注册实现了Ordered接口的BeanPostProcessor
 *       5)没有实现优先级接口的BeanPostProcessor
 *       6) 注册BeanPostProcessor,实际上就是创建BeanPostProcessor对象,保存在容器中
 * 				创建internalAutoProxyCreator的BeanPostProcessor(AnnotationAwareAspectJAutoProxyCreator)
 * 				1、创建Bean的实例
 * 				2、populateBean:给bean的各种属性赋值
 * 				3、initializeBean:初始化bean
 * 						1、invokeAwareMethods() :
 * 						2、applyBeanPostProcessorsBeforeInitialization() 执行后置处理器postProcessBeforeInitialization
 * 						3、invokeInitMethods():执行自定义的初始化方法
 * 						4、applyBeanPostProcessorsAfterInitialization()  执行后置处理器postProcessAfterInitialization
 * 				4、BeanPostProcessor(AnnotationAwareAspectJAutoProxyCreator)创建成功
 *       7) 把BeanPostProcessor注册到BeanFactory中:
 *          beanFactory.addBeanPostProcessor(beanPostProcessor)
 *  ========以上是创建和注册AnnotationAwareAspectJAutoProxyCreator的过程 ========
 *
 *    4、完成BeanFactory剩余的初始化工作:创建剩下的单实例bean
 *       1) 遍历获取容器所有的bean,依次创建对象
 *       2)、创建bean
 *
 *  AnnotationAwareAspectJAutoProxyCreator【InstantiationAwareBeanPostProcessor】的作用
 *  1、每一个bean创建之前,调用postProcessBeforeInstantiation();
 *     关心MathCalculator和LogAspect的创建
 *     1) 判断当前bean是否在advisedBean中(保存了所有需要增强的bean)
 *     2)  判断当前bean是否是基础类型的Advice、Pointcut、Aspect。。。
 *
 *  2、创建对象 调用postProcessAfterInitialization:
 *      1)、获取bean的所有增强器
 *         1)获取候选当所有增强器(找到哪些通知方法是需要切入当前bean方法的)
 *         2)获取到能在bean使用的增强器
 *         3)给增强器排序
 *      2)、保存当前bean在advisedBeans中
 *      3)、创建bean的代理对象,创建当前bean的代理对象
 *         1)获取所有增强器(通知方法)
 *         2)保存到proxyFactory中
 *         3)创建代理对象
 *              JdkDynamicAopProxy(config);jdk动态代理
 * 				ObjenesisCglibAopProxy(config);cglib动态代理
 * 	    4)、给容器返回当前组件使用cglib增强了的代理对象
 * 	    5)、以后容器中获取到的就是这个组件的代理对象,执行目标方法的时候,代理对象就会执行通知方法
 * 	3、目标方法执行
 * 	    容器中保存了组件的代理对象(cglib增强后的对象),这个对象里面保存了详细信息
 * 	    1)CglibAopProxy.intercept()拦截目标方法的执行
 * 	    2)根据ProxyFactory对象获取将要执行的目标方法的拦截器链
 * 	    3)没有拦截器链,直接执行目标方法
 * 	       拦截器链(每一个通知方法又被包装为方法拦截器,利用MethodInterceptor机制)
 * 	    4)如果有拦截器链,把需要执行的目标对象,目标方法,拦截器链等信息传入创建一个CglibMethodInvocation对象
 * 	       并调用Object retval = mi.proceed()
 * 	    5)拦截器链的触发过程
 * 	       1)如果没有拦截器执行目标方法,或者拦截器的索引和拦截器数组-1大小一样,执行目标方法
 * 	       2)链式获取每一个拦截器,拦截器执行invoke方法,每一个拦截器等待下一个拦截器执行完成返回以后再来执行
 * 	          拦截器链的机制,保证通知方法与目标方法的执行顺序
 *
 * 	 总结:
 * 	   1)@EnableAspectJAutoProxy注解开启AOP功能
 * 	   2)@EnableAspectJAutoProxy会给容器注册一个组件AnnotationAwareAspectJAutoProxyCreator
 *     3)AnnotationAwareAspectJAutoProxyCreator是一个后置处理器
 *     4)容器的创建流程:
 *        1)registerBeanPostProcessors()注册后置处理器:创建AnnotationAwareAspectJAutoProxyCreator
 *        2)finishBeanFactoryInitialization()初始化剩下的单实例bean
 *           1)创建业务逻辑组件和切面组件
 *           2)AnnotationAwareAspectJAutoProxyCreator拦截组件的创建过程
 *           3)组件创建完成之后,判断组件是否需要增强
 *              是:切面的通知方法包装成增强器(Advisor);给业务逻辑组件创建一个代理对象
 *     5)执行目标方便
 *        1)代理对象执行目标方法
 *        2)CglibAopProxy.intercept()拦截目标方法的执行
 *          1)得到目标方法的拦截器链(增强器包装成拦截器MethodInterceptor)
 *          2) 利用拦截器的链式机制,依次进入每一个拦截器进行执行
 *          3)效果:
 *              正常执行:前置通知-->目标方法-->后置通知-->返回通知
 *              异常执行:前置通知-->目标方法-->后置通知-->异常通知
 *
 *
 */
发布了142 篇原创文章 · 获赞 345 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/zhengchao1991/article/details/85782697
今日推荐