码迷,mamicode.com
首页 > 编程语言 > 详细

Spring中自动创建代理器

时间:2020-01-03 14:19:14      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:Once   shm   注解   handle   ports   抽象类   动态代理   tcl   attribute   

1、AbstractAutoProxyCreator

   该类继承关系如代码所示:

public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
        implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {

首先,它继承了ProxyProcessorSupport,查看该类:

// 显然,它是个ProxyConfig 拥有AOP的基本配置
public class ProxyProcessorSupport extends ProxyConfig implements Ordered, BeanClassLoaderAware, AopInfrastructureBean {
    ...
    // 这是它最重要的一个方法:就是把该bean所有的实现的接口 都作用在ProxyFactory 上 当然是有过滤得
    protected void evaluateProxyInterfaces(Class<?> beanClass, ProxyFactory proxyFactory) {
        // 拿到该类所有实现的接口们~~~~
        Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, getProxyClassLoader());

        // 标记:是否存在“有问题的”代理接口  默认是false
        boolean hasReasonableProxyInterface = false;
        for (Class<?> ifc : targetInterfaces) {
            
            //判断这些接口是否是“有问题的”:既我们需要处理的
            if (!isConfigurationCallbackInterface(ifc) && !isInternalLanguageInterface(ifc) &&
                    ifc.getMethods().length > 0) {
                hasReasonableProxyInterface = true;
                break;
            }
        }
        
        // 说明除开哪些接口外,但凡有一个有用的接口,就add进去(这样就会采用JDK的动态代理了)
        if (hasReasonableProxyInterface) {
            for (Class<?> ifc : targetInterfaces) {
                proxyFactory.addInterface(ifc);
            }
        }
        // 否则直接采用CGLIB
        else {
            proxyFactory.setProxyTargetClass(true);
        }
    }
    // InitializingBean...Aware接口的子接口等等这些回调性质的接口
    protected boolean isConfigurationCallbackInterface(Class<?> ifc) {
        return (InitializingBean.class == ifc || DisposableBean.class == ifc || Closeable.class == ifc ||
                AutoCloseable.class == ifc || ObjectUtils.containsElement(ifc.getInterfaces(), Aware.class));
    }
    // 接口名称为这些的  也就是spring aop自己的东西
    protected boolean isInternalLanguageInterface(Class<?> ifc) {
        return (ifc.getName().equals("groovy.lang.GroovyObject") ||
                ifc.getName().endsWith(".cglib.proxy.Factory") ||
                ifc.getName().endsWith(".bytebuddy.MockAccess"));
    }
    
}

里面最重要的方法是evaluateProxyInterfaces(),在AbstractAutoProxyCreator类中会调用该方法,判断使用哪种代理方式。

接下来将AbstractAutoProxyCreator贴在如下:

 

    public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
        implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {

    /**
     * Convenience constant for subclasses: Return value for "do not proxy".
     * @see #getAdvicesAndAdvisorsForBean
     */
    protected static final Object[] DO_NOT_PROXY = null;

    /**
     * Convenience constant for subclasses: Return value for
     * "proxy without additional interceptors, just the common ones".
     * @see #getAdvicesAndAdvisorsForBean
     */
    protected static final Object[] PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS = new Object[0];


    /** Logger available to subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

    /** Default is global AdvisorAdapterRegistry */
    private AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

    /**
     * Indicates whether or not the proxy should be frozen. Overridden from super
     * to prevent the configuration from becoming frozen too early.
     */
    private boolean freezeProxy = false;

    /** Default is no common interceptors */
    private String[] interceptorNames = new String[0];

    private boolean applyCommonInterceptorsFirst = true;

    private TargetSourceCreator[] customTargetSourceCreators;

    private BeanFactory beanFactory;

    private final Set<String> targetSourcedBeans =
            Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));

    private final Map<Object, Object> earlyProxyReferences = new ConcurrentHashMap<Object, Object>(16);

    private final Map<Object, Class<?>> proxyTypes = new ConcurrentHashMap<Object, Class<?>>(16);

    private final Map<Object, Boolean> advisedBeans = new ConcurrentHashMap<Object, Boolean>(256);


    /**
     * Set whether or not the proxy should be frozen, preventing advice
     * from being added to it once it is created.
     * <p>Overridden from the super class to prevent the proxy configuration
     * from being frozen before the proxy is created.
     */
    @Override
    public void setFrozen(boolean frozen) {
        this.freezeProxy = frozen;
    }

    @Override
    public boolean isFrozen() {
        return this.freezeProxy;
    }

    /**
     * Specify the {@link AdvisorAdapterRegistry} to use.
     * <p>Default is the global {@link AdvisorAdapterRegistry}.
     * @see org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry
     */
    public void setAdvisorAdapterRegistry(AdvisorAdapterRegistry advisorAdapterRegistry) {
        this.advisorAdapterRegistry = advisorAdapterRegistry;
    }

    /**
     * Set custom {@code TargetSourceCreators} to be applied in this order.
     */
    public void setCustomTargetSourceCreators(TargetSourceCreator... targetSourceCreators) {
        this.customTargetSourceCreators = targetSourceCreators;
    }

    /**
     * Set the common interceptors. These must be bean names in the current factory.
     * They can be of any advice or advisor type Spring supports.
     */
    public void setInterceptorNames(String... interceptorNames) {
        this.interceptorNames = interceptorNames;
    }

    /**
     * Set whether the common interceptors should be applied before bean-specific ones.
     * Default is "true"; else, bean-specific interceptors will get applied first.
     */
    public void setApplyCommonInterceptorsFirst(boolean applyCommonInterceptorsFirst) {
        this.applyCommonInterceptorsFirst = applyCommonInterceptorsFirst;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    /**
     * Return the owning {@link BeanFactory}.
     * May be {@code null}, as this post-processor doesn‘t need to belong to a bean factory.
     */
    protected BeanFactory getBeanFactory() {
        return this.beanFactory;
    }


    @Override
    public Class<?> predictBeanType(Class<?> beanClass, String beanName) {
        if (this.proxyTypes.isEmpty()) {
            return null;
        }
        Object cacheKey = getCacheKey(beanClass, beanName);
        return this.proxyTypes.get(cacheKey);
    }

    @Override
    public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
        return null;
    }
    // getEarlyBeanReference()它是为了解决单例bean之间的循环依赖问题,提前将代理对象暴露出去
    @Override
    public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
        Object cacheKey = getCacheKey(bean.getClass(), beanName);
        this.earlyProxyReferences.put(cacheKey, bean);
        return wrapIfNecessary(bean, beanName, cacheKey);
    }

    // 这个很重要,在Bean实例化之前,先给一个机会,看看缓存里有木有,有就直接返回得了
    // 简单的说:其主要目的在于如果用户使用了自定义的TargetSource对象,则直接使用该对象生成目标对象,而不会使用Spring的默认逻辑生成目标对象
    // 并且这里会判断各个切面逻辑是否可以应用到当前bean上,如果是基础设施类或者可以进行跳过的会直接返回null
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        Object cacheKey = getCacheKey(beanClass, beanName);

        if (beanName == null || !this.targetSourcedBeans.contains(beanName)) {
            if (this.advisedBeans.containsKey(cacheKey)) {
                return null;
            }
            if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
                this.advisedBeans.put(cacheKey, Boolean.FALSE);
                return null;
            }
        }

        // Create proxy here if we have a custom TargetSource.
        if (beanName != null) {
            TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
            if (targetSource != null) {
                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
    * */
    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) {
        return true;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }

    /**
     * Create a proxy with the configured interceptors if the bean is
     *  earlyProxyReferences缓存:该缓存用于保存已经创建过代理对象的cachekey,**避免重复创建**
     *  最重要的是方法:wrapIfNecessary(bean, beanName, cacheKey)
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean != null) {
            Object cacheKey = getCacheKey(bean.getClass(), beanName);
            if (this.earlyProxyReferences.remove(cacheKey) != bean) {
                return wrapIfNecessary(bean, beanName, cacheKey);
            }
        }
        return bean;
    }


    /**
     * Build a cache key for the given bean class and bean name.
     */
    protected Object getCacheKey(Class<?> beanClass, String beanName) {
        if (StringUtils.hasLength(beanName)) {
            return (FactoryBean.class.isAssignableFrom(beanClass) ?
                    BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
        }
        else {
            return beanClass;
        }
    }

    /**
     * Wrap the given bean if necessary, i.e. if it is eligible for being proxied.
     */
    protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
        // 若此Bean已经在targetSourcedBeans里,说明已经被代理过,那就直接返回即可
        // (postProcessBeforeInstantiation()中成功创建的代理对象都会将beanName加入到targetSourceBeans中)
        if (beanName != null && this.targetSourcedBeans.contains(beanName)) {
            return bean;
        }
        // 如果该Bean基础框架Bean或者免代理得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) {
            // 缓存起来,赋值为true,说明此key是被代理了的
            this.advisedBeans.put(cacheKey, Boolean.TRUE);
            // 创建这个代理对象
            Object proxy = createProxy(
                    bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
            // 不需要代理,也把这种不需要代理的对象给与缓存起来  赋值为false
            this.proxyTypes.put(cacheKey, proxy.getClass());
            return proxy;
        }

        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }

    /**
     * 判断是否是基础设施类
     */
    protected boolean isInfrastructureClass(Class<?> beanClass) {
        boolean retVal = Advice.class.isAssignableFrom(beanClass) ||
                Pointcut.class.isAssignableFrom(beanClass) ||
                Advisor.class.isAssignableFrom(beanClass) ||
                AopInfrastructureBean.class.isAssignableFrom(beanClass);
        if (retVal && logger.isTraceEnabled()) {
            logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]");
        }
        return retVal;
    }

    /**
     * 判断是否需要跳过,具体由子类进行实现
     */
    protected boolean shouldSkip(Class<?> beanClass, String beanName) {
        return false;
    }

    /**
     * 这个方法也很重要,若我们自己要实现一个TargetSourceCreator ,就可以实现我们自定义的逻辑了
     * 如果没有自定义的customTargetSourceCreators,那么就会返回null
     * beanFactory不能为null,而且其中必须包含beanName的Bean
     */
    protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) {
        // We can‘t create fancy target sources for directly registered singletons.
        if (this.customTargetSourceCreators != null &&
                this.beanFactory != null && this.beanFactory.containsBean(beanName)) {
            for (TargetSourceCreator tsc : this.customTargetSourceCreators) {
                TargetSource ts = tsc.getTargetSource(beanClass, beanName);
                if (ts != null) {
                    // Found a matching TargetSource.
                    if (logger.isDebugEnabled()) {
                        logger.debug("TargetSourceCreator [" + tsc +
                                "] found custom TargetSource for bean with name ‘" + beanName + "‘");
                    }
                    return ts;
                }
            }
        }
        // No custom TargetSource found.
        return null;
    }

    /**
     * Create an AOP proxy for the given bean.
     */
    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);
        // 看看是否是基于类的代理(CGLIB),若表面上是基于接口的代理  我们还需要进一步去检测
        if (!proxyFactory.isProxyTargetClass()) {
            // shouldProxyTargetClass方法用于判断是否应该使用targetClass类而不是接口来进行代理
            if (shouldProxyTargetClass(beanClass, beanName)) {
                proxyFactory.setProxyTargetClass(true);
            }
            else {
                //调用的是父类ProxyProcessorSupport方法,为proxyFactory添加接口,没有接口直接设置setProxyTargetClass(true)
                evaluateProxyInterfaces(beanClass, proxyFactory);
            }
        }
        // buildAdvisors:整理合并得到最终的advisors
        Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
        proxyFactory.addAdvisors(advisors);
        proxyFactory.setTargetSource(targetSource);
        // 这个方法是交给子类的,子类可以继续去定制此proxyFactory
        customizeProxyFactory(proxyFactory);

        proxyFactory.setFrozen(this.freezeProxy);
        if (advisorsPreFiltered()) {
            proxyFactory.setPreFiltered(true);
        }

        return proxyFactory.getProxy(getProxyClassLoader());
    }
    /**
     * Determine whether the given bean should be proxied with its target class rather than its interfaces.
     * <p>Checks the {@link AutoProxyUtils#PRESERVE_TARGET_CLASS_ATTRIBUTE "preserveTargetClass" attribute}
     * of the corresponding bean definition.
     */
    protected boolean shouldProxyTargetClass(Class<?> beanClass, String beanName) {
        return (this.beanFactory instanceof ConfigurableListableBeanFactory &&
                AutoProxyUtils.shouldProxyTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName));
    }

    /**
     * Return whether the Advisors returned by the subclass are pre-filtered
     * to match the bean‘s target class already, allowing the ClassFilter check
     * to be skipped when building advisors chains for AOP invocations.
     * <p>Default is {@code false}. Subclasses may override this if they
     * will always return pre-filtered Advisors.
     */
    protected boolean advisorsPreFiltered() {
        return false;
    }

    /**
     * Determine the advisors for the given bean, including the specific interceptors
     * as well as the common interceptor, all adapted to the Advisor interface.
     * 将specificInterceptors中拦截器和commonInterceptors都转换成Advisor的接口类型
     */
    protected Advisor[] buildAdvisors(String beanName, Object[] specificInterceptors) {
        // Handle prototypes correctly...
        Advisor[] commonInterceptors = resolveInterceptorNames();

        List<Object> allInterceptors = new ArrayList<Object>();
        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));
                }
            }
        }
        if (logger.isDebugEnabled()) {
            int nrOfCommonInterceptors = commonInterceptors.length;
            int nrOfSpecificInterceptors = (specificInterceptors != null ? specificInterceptors.length : 0);
            logger.debug("Creating implicit proxy for bean ‘" + beanName + "‘ with " + nrOfCommonInterceptors +
                    " common interceptors and " + nrOfSpecificInterceptors + " specific interceptors");
        }

        Advisor[] advisors = new Advisor[allInterceptors.size()];
        for (int i = 0; i < allInterceptors.size(); i++) {
            advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i));
        }
        return advisors;
    }

    /**
     * Resolves the specified interceptor names to Advisor objects.
     */
    private Advisor[] resolveInterceptorNames() {
        ConfigurableBeanFactory cbf = (this.beanFactory instanceof ConfigurableBeanFactory ?
                (ConfigurableBeanFactory) this.beanFactory : null);
        List<Advisor> advisors = new ArrayList<Advisor>();
        for (String beanName : this.interceptorNames) {
            if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) {
                Object next = this.beanFactory.getBean(beanName);
                advisors.add(this.advisorAdapterRegistry.wrap(next));
            }
        }
        return advisors.toArray(new Advisor[advisors.size()]);
    }

    /**
     * Subclasses may choose to implement this: for example,
     * to change the interfaces exposed.
     */
    protected void customizeProxyFactory(ProxyFactory proxyFactory) {
    }


    /**
     * Return whether the given bean is to be proxied, what additional
     * advices (e.g. AOP Alliance interceptors) and advisors to apply.
     */
    protected abstract Object[] getAdvicesAndAdvisorsForBean(
            Class<?> beanClass, String beanName, TargetSource customTargetSource) throws BeansException;

}

2、AbstractAdvisorAutoProxyCreator 

该类继承了AbstractAutoProxyCreator,它的核心方法是实现了父类的:getAdvicesAndAdvisorsForBean来获取Advisor

public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {

    // 这个类是重点,已经在随机中写过,主要就是从工厂中获取所有的Advisor
    @Nullable
    private BeanFactoryAdvisorRetrievalHelper advisorRetrievalHelper;

    // 重写了setBeanFactory方法,事需要保证bean工厂必须是ConfigurableListableBeanFactory
    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        super.setBeanFactory(beanFactory);
        if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
            throw new IllegalArgumentException(
                    "AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory);
        }
        // 就这一句话:this.advisorRetrievalHelper = new BeanFactoryAdvisorRetrievalHelperAdapter(beanFactory)
        // 对Helper进行初始化,找advisor最终事委托给他了的
        // BeanFactoryAdvisorRetrievalHelperAdapter继承自BeanFactoryAdvisorRetrievalHelper,为私有内部类,主要重写了isEligibleBean()方法,调用.this.isEligibleAdvisorBean(beanName)方法
        initBeanFactory((ConfigurableListableBeanFactory) beanFactory);
    }

    // 这是复写父类的方法,也是实现代理方式。找到作用在这个Bean里面的切点方法
    // 当然 最终最终事委托给BeanFactoryAdvisorRetrievalHelper去做的
    @Override
    @Nullable
    protected Object[] getAdvicesAndAdvisorsForBean(
            Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {

        // findEligibleAdvisors:显然这个是具体的实现方法了。
        // eligible:合格的  合适的
        List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
        if (advisors.isEmpty()) {
            return DO_NOT_PROXY;
        }
        return advisors.toArray();
    }

    // 找出合适的Advisor们~~~  主要分了下面几步
    protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {

        // 首先找出所有的候选的Advisors,(根据名字判断)实现见下面~~~~
        List<Advisor> candidateAdvisors = findCandidateAdvisors();
        // 对上面找到的候选的Advisors们,进行过滤操作~~~  看看Advisor能否被用在Bean上(根据Advisor的PointCut判断)
        // 主要依赖于AopUtils.findAdvisorsThatCanApply()方法  在工具类讲解中有详细分析的
        // 逻辑简单概述为:看目标类是不是符合代理对象的条件,如果符合就把Advisor加到集合中,最后返回集合
        // 简单的说:它就是会根据ClassFilter和MethodMatcher等等各种匹配。(但凡只有有一个方法被匹配上了,就会给他创建代理类了)
        // 方法用的ReflectionUtils.getAllDeclaredMethods,**因此哪怕是私有方法,匹配上都会给创建的代理对象,这点务必要特别特别的注意**
        List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);

        //提供一个钩子。子类可以复写此方法  然后对eligibleAdvisors进行处理(增加/删除/修改等等)
        // AspectJAwareAdvisorAutoProxyCreator提供了实现
        extendAdvisors(eligibleAdvisors);

        // 如果有,那就排序
        if (!eligibleAdvisors.isEmpty()) {
            // 默认排序方式:AnnotationAwareOrderComparator.sort()排序  这个排序和Order接口有关~~~
            // 但是子类:AspectJAwareAdvisorAutoProxyCreator有复写此排序方法,需要特别注意~~~
            eligibleAdvisors = sortAdvisors(eligibleAdvisors);
        }
        return eligibleAdvisors;
    }


    // 找到候选的Advisor们~~~~   抽象类自己的实现,是直接把这件事委托给了advisorRetrievalHelper
    // 关于它的具体逻辑  后文问详细分析  毕竟属于核心逻辑
    // AnnotationAwareAspectJAutoProxyCreator对它有复写
    protected List<Advisor> findCandidateAdvisors() {
        Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
        return this.advisorRetrievalHelper.findAdvisorBeans();
    }

    // 判断给定的BeanName这个Bean,是否是合格的(BeanFactoryAdvisorRetrievalHelper里会用到这个属性)
    // 其中:DefaultAdvisorAutoProxyCreator和InfrastructureAdvisorAutoProxyCreator有复写
    protected boolean isEligibleAdvisorBean(String beanName) {
        return true;
    }

    // 此处复写了父类的方法,返回true了,表示
    @Override
    protected boolean advisorsPreFiltered() {
        return true;
    }
}

这个抽象类主要是提供getAdvicesAndAdvisorsForBean()这个方法的获取模版,虽然它没有提供抽象方法给子类去实现,但子类复写了protected方法,改变了一些默认行为。但是各个实现类都各有不同,现在我们看看实现:

DefaultAdvisorAutoProxyCreator、AspectJAwareAdvisorAutoProxyCreator、InfrastructureAdvisorAutoProxyCreator

4、以下只介绍:AspectJAwareAdvisorAutoProxyCreator

该类主要来处理AspectJ切面的。这也是当下最流行,也是功能最为强大的一种方式;
// @since 2.0
public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {

    // 默认的排序器,它就不是根据Order来了,而是根据@Afeter @Before类似的标注来排序
    private static final Comparator<Advisor> DEFAULT_PRECEDENCE_COMPARATOR = new AspectJPrecedenceComparator();

    // 核心逻辑:它重写了排序
    // 这个排序和`org.aspectj.util`提供的PartialOrder和PartialComparable有关 具体不详叙了
    // 这块排序算法还是比较复杂的,控制着最终的执行顺序~
    protected List<Advisor> sortAdvisors(List<Advisor> advisors) {
        ...
    }
// 当使用Aspect的PointCut或者是Aspect的Adcice都会使用到
    // 它的作用:(若存在AspectJ的Advice),就会在advisors的第一个位置加入`ExposeInvocationInterceptor.ADVISOR`这个advisor
    @Override
    protected void extendAdvisors(List<Advisor> candidateAdvisors) {
        AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors);
    }

    
    @Override
    protected boolean shouldSkip(Class<?> beanClass, String beanName) {
        List<Advisor> candidateAdvisors = findCandidateAdvisors();
        
        // 这个相当于AspectJPointcutAdvisor的子类不要拦截、AspectJ切面自己自己的所有方法不要去拦截。。。
        for (Advisor advisor : candidateAdvisors) {
            if (advisor instanceof AspectJPointcutAdvisor &&
                    ((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) {
                return true;
            }
        }
        // 父类返回的false
        return super.shouldSkip(beanClass, beanName);
    }
    ...
}

5、AnnotationAwareAspectJAutoProxyCreator

  首先AnnotationAwareAspectJAutoProxyCreator它是AspectJAwareAdvisorAutoProxyCreator的子类。

然后从名字中可议看出,它和注解有关。因此其实我们的@EnableAspectJAutoProxy它导入的就是这个自动代理创建器去帮我们创建和AspectJ相关的代理对象的。
     

// @since 2.0
public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {

    @Nullable
    private List<Pattern> includePatterns;
    //唯一实现类:ReflectiveAspectJAdvisorFactory
    // 作用:基于@Aspect时,创建Spring AOP的Advice
    // 里面会对标注这些注解Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class的方法进行排序
    // 然后把他们都变成Advisor( getAdvisors()方法 )
    @Nullable
    private AspectJAdvisorFactory aspectJAdvisorFactory;
    //该工具类用来从bean容器,也就是BeanFactory中获取所有使用了@AspectJ注解的bean
    //就是这个方法:aspectJAdvisorsBuilder.buildAspectJAdvisors()
    @Nullable
    private BeanFactoryAspectJAdvisorsBuilder aspectJAdvisorsBuilder;


    // 很显然,它还支持我们自定义一个正则的模版
    // isEligibleAspectBean()该方法使用此模版,从而决定使用哪些Advisor
    public void setIncludePatterns(List<String> patterns) {
        this.includePatterns = new ArrayList<>(patterns.size());
        for (String patternText : patterns) {
            this.includePatterns.add(Pattern.compile(patternText));
        }
    }
    
    // 可以自己实现一个AspectJAdvisorFactory  否则用默认的ReflectiveAspectJAdvisorFactory
    public void setAspectJAdvisorFactory(AspectJAdvisorFactory aspectJAdvisorFactory) {
        Assert.notNull(aspectJAdvisorFactory, "AspectJAdvisorFactory must not be null");
        this.aspectJAdvisorFactory = aspectJAdvisorFactory;
    }

    // 此处一定要记得调用:super.initBeanFactory(beanFactory);
    @Override
    protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        super.initBeanFactory(beanFactory);
        if (this.aspectJAdvisorFactory == null) {
            this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);
        }
        this.aspectJAdvisorsBuilder = new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);
    }


    // 拿到所有的候选的advisor们。请注意:调用了父类的super.findCandidateAdvisors()  去容器里找出来一些
    // 然后,然后自己又通过aspectJAdvisorsBuilder.buildAspectJAdvisors()  解析@Aspect的方法得到一些Advisor
    @Override
    protected List<Advisor> findCandidateAdvisors() {
        List<Advisor> advisors = super.findCandidateAdvisors();
        if (this.aspectJAdvisorsBuilder != null) {
            advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
        }
        return advisors;
    }
    
    // 如果该Bean自己本身就是一个@Aspect, 那也认为是基础主键,不要切了
    @Override
    protected boolean isInfrastructureClass(Class<?> beanClass) {
        return (super.isInfrastructureClass(beanClass) ||
                (this.aspectJAdvisorFactory != null && this.aspectJAdvisorFactory.isAspect(beanClass)));
    }

    // 拿传入的正则模版进行匹配(没传就返回true,所有的Advisor都会生效)
    protected boolean isEligibleAspectBean(String beanName) {
        if (this.includePatterns == null) {
            return true;
        }
        else {
            for (Pattern pattern : this.includePatterns) {
                if (pattern.matcher(beanName).matches()) {
                    return true;
                }
            }
            return false;
        }
    }
    ...
}

Spring中自动创建代理器

标签:Once   shm   注解   handle   ports   抽象类   动态代理   tcl   attribute   

原文地址:https://www.cnblogs.com/mayang2465/p/12144329.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!