美文网首页Spring工作生活
Spring aspectj-autoproxy流程

Spring aspectj-autoproxy流程

作者: 晴天哥_王志 | 来源:发表于2019-07-06 09:32 被阅读0次

    开篇

     这篇文章主要想描述下Spring中通过aspectj修饰的代理的流程,在Spring当中Proxy无处不在,在这篇文章中我们尝试按照下面的流程进行描述,按照

    • 1、aspectj-autoproxy解析生成aspectj-autoproxy的BeanDefinition。
    • 2、Spring加载BeanDefinition的注册BeanPostProcessors对象。
    • 3、Bean初始化的过程中回调创建Proxy对象。
    • 4、Proxy创建过程获取Advisor对象生成Proxy对象。

     在这里有一个问题特别需要理清楚,就是aspectj-autoproxy对应的Bean如何和普通的Bean之间如何串联起来的?

     核心在于Spring 加载BeanDefinition过程中加载了aspectj-autoproxy对应的BeanDefinition后,refresh()方法内通过registerBeanPostProcessors()方法会把所有BeanPostProcessor类型的Bean对象进行注册。

     AnnotationAwareAspectJAutoProxyCreator类就是BeanPostProcessor类型。
     普通Bean初始化的过程中最后会遍历所有BeanPostProcessors进行初始化完成串联。

     总结起来整体流程,1、加载BeanDefinition(过程中会加载aspectj-autoproxy的Bean),2、注册Bean初始化后置对象registerBeanPostProcessors,3、Bean初始化后执行BeanPostProcessors执行后置操作。

    aspectj-autoproxy解析

    public class AopNamespaceHandler extends NamespaceHandlerSupport {
        public void init() {
            registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser());
            registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());
            registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator());
            registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
        }
    }
    
    -------
    
    class AspectJAutoProxyBeanDefinitionParser implements BeanDefinitionParser {
    
        public BeanDefinition parse(Element element, ParserContext parserContext) {
            AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);
            extendBeanDefinition(element, parserContext);
            return null;
        }
    }
    
    -------
    
    public abstract class AopNamespaceUtils {
    
        public static final String PROXY_TARGET_CLASS_ATTRIBUTE = "proxy-target-class";
        private static final String EXPOSE_PROXY_ATTRIBUTE = "expose-proxy";
    
        public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary(
                ParserContext parserContext, Element sourceElement) {
    
            // 确认生成AspectJ的BeanDefinition对象
            BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(
                    parserContext.getRegistry(), parserContext.extractSource(sourceElement));
    
            // 确认是否使用cglib代理
            useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement);
    
            registerComponentIfNecessary(beanDefinition, parserContext);
        }
    
        private static void useClassProxyingIfNecessary(BeanDefinitionRegistry registry, @Nullable Element sourceElement) {
    
            if (sourceElement != null) {
                // proxy-target-class 设置是否使用类代理
                boolean proxyTargetClass = Boolean.parseBoolean(sourceElement.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE));
                if (proxyTargetClass) {
                    AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
                }
                // expose-proxy 设置是否设置暴露
                boolean exposeProxy = Boolean.parseBoolean(sourceElement.getAttribute(EXPOSE_PROXY_ATTRIBUTE));
                if (exposeProxy) {
                    AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
                }
            }
        }
    }
    
    
    public abstract class AopConfigUtils {
    
        public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(
                BeanDefinitionRegistry registry, @Nullable Object source) {
            // AnnotationAwareAspectJAutoProxyCreator核心对象
            return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
        }
    }
    
    AnnotationAwareAspectJAutoProxyCreator

    说明:

    • AnnotationAwareAspectJAutoProxyCreator继承了BeanPostProcessor并注册到BeanFactory当中。
    • Spring在Bean实例化后会调用BeanPostProcessor的postProcessAfterInitialization方法。
    • 分析的入口选择BeanPostProcessor的postProcessAfterInitialization方法。

    初始化BeanPostProcessors

    public abstract class AbstractApplicationContext extends DefaultResourceLoader
            implements ConfigurableApplicationContext {
    
        public void refresh() throws BeansException, IllegalStateException {
            synchronized (this.startupShutdownMonitor) {
    
                prepareRefresh();
                ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
                prepareBeanFactory(beanFactory);
    
                try {
                    // 省略非重要代码
    
                    // 注册Bean初始化后的处理器
                    registerBeanPostProcessors(beanFactory);
                }
                catch (BeansException ex) {
                }
                finally {
                }
            }
        }
    
        protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
            PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
        }
    }
    
    
    
    final class PostProcessorRegistrationDelegate {
    
        public static void registerBeanPostProcessors(
                ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
    
            // 获取BeanPostProcessor类型的BeanName
            String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
    
            int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
            beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
    
            List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
            List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
            List<String> orderedPostProcessorNames = new ArrayList<>();
            List<String> nonOrderedPostProcessorNames = new ArrayList<>();
            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);
                }
            }
    
            sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
            registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
    
            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);
    
            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);
            sortPostProcessors(internalPostProcessors, beanFactory);
            registerBeanPostProcessors(beanFactory, internalPostProcessors);
    
            beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
        }
    }
    

    说明:

    • 核心在于加载完BeanDefinition后执行registerBeanPostProcessors,将所有BeanPostProcessor类型的Bean注册到beanFactory。
    • 注册到beanFactory的BeanPostProcessor会在后续普通Bean初始化后被调用。

    Bean初始化回调BeanPostProcessors

    public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
            implements AutowireCapableBeanFactory {
    
        protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                    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) {
            }
            if (mbd == null || !mbd.isSynthetic()) {
                // 初始化后置回调方法
                wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
            }
    
            return wrappedBean;
        }
    
        public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
                throws BeansException {
    
            Object result = existingBean;
            // 批量初始化的后置方法
            for (BeanPostProcessor processor : getBeanPostProcessors()) {
                Object current = processor.postProcessAfterInitialization(result, beanName);
                if (current == null) {
                    return result;
                }
                result = current;
            }
            return result;
        }
    }
    

    说明:

    • initializeBean的最后操作执行applyBeanPostProcessorsAfterInitialization()方法。
    • 在方法内部遍历所有BeanPostProcessors并调用postProcessAfterInitialization方法。
    • 这里完成了注册的BeanPostProcessors和BeanPostProcessors的调用,所有的Bean的初始化后都会调用注册的BeanPostProcessors完成串联。

    Proxy创建流程

    public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
            implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
    
        public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
            if (bean != null) {
                Object cacheKey = getCacheKey(bean.getClass(), beanName);
                if (this.earlyProxyReferences.remove(cacheKey) != bean) {
                    return wrapIfNecessary(bean, beanName, cacheKey);
                }
            }
            return bean;
        }
    
    
        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;
            }
    
            /*
             * 如果是基础设施类(Pointcut、Advice、Advisor 等接口的实现类),或是应该跳过的类,
             * 则不应该生成代理,此时直接返回 bean
             */ 
            if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
                this.advisedBeans.put(cacheKey, Boolean.FALSE);
                return bean;
            }
    
            // 为目标 bean 查找合适的通知器
            Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
            /*
             * 若 specificInterceptors != null,即 specificInterceptors != DO_NOT_PROXY,
             * 则为 bean 生成代理对象,否则直接返回 bean
             */ 
            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());
                /*
                 * 返回代理对象,此时 IOC 容器输入 bean,得到 proxy。此时,
                 * beanName 对应的 bean 是代理对象,而非原始的 bean
                 */ 
                return proxy;
            }
    
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return bean;
        }
    
    }
    

    说明:

    • postProcessAfterInitialization内部执行wrapIfNecessary判定是否需要创建Proxy。
    • 为目标bean查找合适的通知器,为bean生成代理对象,返回代理对象。
    • createProxy()为目标bean生成代理对象,持续关注createProxy方法。

    获取Advisor对象

    public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
    
        protected Object[] getAdvicesAndAdvisorsForBean(
                Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
    
            List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
            if (advisors.isEmpty()) {
                return DO_NOT_PROXY;
            }
            return advisors.toArray();
        }
    
    
        protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
    
            // 查找所有的通知器
            List<Advisor> candidateAdvisors = findCandidateAdvisors();
    
            /*
             * 筛选可应用在 beanClass 上的 Advisor,通过 ClassFilter 和 MethodMatcher
             * 对目标类和方法进行匹配
             */
            List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
    
            // 拓展操作
            extendAdvisors(eligibleAdvisors);
            if (!eligibleAdvisors.isEmpty()) {
                eligibleAdvisors = sortAdvisors(eligibleAdvisors);
            }
            return eligibleAdvisors;
        }
    
    
        protected List<Advisor> findCandidateAdvisors() {
            return this.advisorRetrievalHelper.findAdvisorBeans();
        }
    
    
        protected List<Advisor> findAdvisorsThatCanApply(
                List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
    
            ProxyCreationContext.setCurrentProxiedBeanName(beanName);
            try {
                return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
            }
            finally {
                ProxyCreationContext.setCurrentProxiedBeanName(null);
            }
        }
    }
    
    
    
    public class BeanFactoryAdvisorRetrievalHelper {
    
        public List<Advisor> findAdvisorBeans() {
            // cachedAdvisorBeanNames 是 advisor 名称的缓存
            String[] advisorNames = this.cachedAdvisorBeanNames;
    
            /*
             * 如果 cachedAdvisorBeanNames 为空,这里到容器中查找,
             * 并设置缓存,后续直接使用缓存即可
             */ 
            if (advisorNames == null) {
                // 从容器中查找 Advisor 类型 bean 的名称
                advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                        this.beanFactory, Advisor.class, true, false);
                // 设置缓存
                this.cachedAdvisorBeanNames = advisorNames;
            }
            if (advisorNames.length == 0) {
                return new ArrayList<>();
            }
    
            List<Advisor> advisors = new ArrayList<>();
            // 遍历 advisorNames
            for (String name : advisorNames) {
                /*
                 * 调用 getBean 方法从容器中获取名称为 name 的 bean,
                 * 并将 bean 添加到 advisors 中
                 */ 
                if (isEligibleBean(name)) {
                    if (this.beanFactory.isCurrentlyInCreation(name)) {
                    }
                    else {
                        try {
                            advisors.add(this.beanFactory.getBean(name, Advisor.class));
                        }
                        catch (BeanCreationException ex) {
                        }
                    }
                }
            }
            return advisors;
        }
    }
    

    说明:

    • 从容器中查找Advisor类型bean的名称,然后根据bean的名称获取advisor的对象。
    • 这部分逻辑就是去BeanFactory查找Advisor类型的bean类型并返回bean的对象。

    创建Proxy

    public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
            implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
    
        protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
                @Nullable Object[] specificInterceptors, TargetSource targetSource) {
    
            if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
                AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
            }
    
            ProxyFactory proxyFactory = new ProxyFactory();
            proxyFactory.copyFrom(this);
    
            if (!proxyFactory.isProxyTargetClass()) {
                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());
        }
    
    
        protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] specificInterceptors) {
    
            Advisor[] commonInterceptors = resolveInterceptorNames();
            List<Object> allInterceptors = new ArrayList<>();
    
            if (specificInterceptors != null) {
                allInterceptors.addAll(Arrays.asList(specificInterceptors));
                if (commonInterceptors.length > 0) {
                    if (this.applyCommonInterceptorsFirst) {
                        allInterceptors.addAll(0, Arrays.asList(commonInterceptors));
                    }
                    else {
                        allInterceptors.addAll(Arrays.asList(commonInterceptors));
                    }
                }
            }
    
            Advisor[] advisors = new Advisor[allInterceptors.size()];
            for (int i = 0; i < allInterceptors.size(); i++) {
                advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i));
            }
            return advisors;
        }
    }
    

    说明:

    • buildAdvisors负责创建advisors。
    • proxyFactory.getProxy()负责创建的代理对象。
    public class ProxyFactory extends ProxyCreatorSupport {
    
        public Object getProxy(@Nullable ClassLoader classLoader) {
            return createAopProxy().getProxy(classLoader);
        }
    }
    
    
    public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
    
        @Override
        public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
            if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
                Class<?> targetClass = config.getTargetClass();
                if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
                    return new JdkDynamicAopProxy(config);
                }
                return new ObjenesisCglibAopProxy(config);
            }
            else {
                return new JdkDynamicAopProxy(config);
            }
        }
    }
    
    class CglibAopProxy implements AopProxy, Serializable {
    
        public Object getProxy(@Nullable ClassLoader classLoader) {
            if (logger.isTraceEnabled()) {
                logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
            }
    
            try {
                Class<?> rootClass = this.advised.getTargetClass();
                Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");
    
                Class<?> proxySuperClass = rootClass;
                if (ClassUtils.isCglibProxyClass(rootClass)) {
                    proxySuperClass = rootClass.getSuperclass();
                    Class<?>[] additionalInterfaces = rootClass.getInterfaces();
                    for (Class<?> additionalInterface : additionalInterfaces) {
                        this.advised.addInterface(additionalInterface);
                    }
                }
    
                // Validate the class, writing log messages as necessary.
                validateClassIfNecessary(proxySuperClass, classLoader);
    
                // Configure CGLIB Enhancer...
                Enhancer enhancer = createEnhancer();
                if (classLoader != null) {
                    enhancer.setClassLoader(classLoader);
                    if (classLoader instanceof SmartClassLoader &&
                            ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
                        enhancer.setUseCache(false);
                    }
                }
                enhancer.setSuperclass(proxySuperClass);
                enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
                enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
                enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));
    
                Callback[] callbacks = getCallbacks(rootClass);
                Class<?>[] types = new Class<?>[callbacks.length];
                for (int x = 0; x < types.length; x++) {
                    types[x] = callbacks[x].getClass();
                }
                // fixedInterceptorMap only populated at this point, after getCallbacks call above
                enhancer.setCallbackFilter(new ProxyCallbackFilter(
                        this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
                enhancer.setCallbackTypes(types);
    
                // Generate the proxy class and create a proxy instance.
                return createProxyClassAndInstance(enhancer, callbacks);
            }
            catch (CodeGenerationException | IllegalArgumentException ex) {
            }
            catch (Throwable ex) {
            }
        }
    }
    
    
    final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
    
        public Object getProxy(@Nullable ClassLoader classLoader) {
            if (logger.isTraceEnabled()) {
                logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
            }
            Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
            findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
            return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
        }
    }
    

    说明:

    • CglibAopProxy基于Cglib实现的Aop代理。
    • JdkDynamicAopProxy基于jdk实现的Aop代理。
    • 代理的如果是Interface对象就使用JdkDynamicAopProxy,否则使用CglibAopProxy。

    参考文章

    Spring AOP 源码分析 - 筛选合适的通知器

    相关文章

      网友评论

        本文标题:Spring aspectj-autoproxy流程

        本文链接:https://www.haomeiwen.com/subject/jgtxhctx.html