Spring中自动创建代理器

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;
        }
    }
    ...
}

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

时间: 2024-10-29 13:47:10

Spring中自动创建代理器的相关文章

自动创建代理

在前面的例子中, 我们都通过ProxyFactoryBean创建织入切面的代理, 每一个需要被代理的bean都需要使用一个ProxyFactoryBean进行配置, 虽然可以使用父子bean进行改造,但还是很麻烦.对于小型系统而言,这种方法还可以将就使用, 但是对于很多需要代理的bean的系统, 再使用这种方法就会很麻烦. 幸运的是, spring为我们提供了自动创建代理的机制, 容器为我们自动生成代理, 把我们从繁琐的配置工作中解放出来.在内部, Spring使用BeanPostFactory

Spring中获取被代理的对象

目录 Spring中获取被代理的对象 获取Spring被代理对象什么时候可能会用到? Spring中获取被代理的对象 Spring中获取被代理的对象 ### 获取Spring被代理对象的JAVA工具类 ? Spring采用CGLIB或者JDK动态代理来实现AOP,那如何获取 被代理对象?通过ApplicationContext.getBean()获取到的对象都是 利用字节码动态生成的 增强对象,那假如我们有场景获取 被代理的对象,方式如下: (封装到工具类形式里面,直接通过getTrueTarg

Spring中自动检测并申明bean

在Spring中申明bean,一般情况是在XML中用<bean id=""  class="">标签来指定一个类并为其取一个id.但是这样效率很低,Spring提供了自动检测并申明bean的方法,讲解如下: 一.自动检测并申明bean的步骤: 1.用<context:component-scan  base-package="com.springinaction.springidol"></context:compo

Spring(六) Spring中的静态代理

在Spring中代理有两种一种是静态代理一种是动态代理 这篇博客想讲一下静态代理 首先要知道什么是静态代理(查找了一下其他博客) 了解一下静态代理满足的条件和他的弊端 1.需要知道核心类(被代理类)是哪一个类,并且有什么方法. 2.非核心的代码需要重复写多次,显得代码的结构臃肿,形成代码冗余. 3.非核心类(代理类)需要实现核心类(被代理类)实现的接口,也就是他们需要实现共同的接口,但是以核心类实现的接口(被代理类)为准. 下面通过一个例子来说明 先声明一个主题接口,接口的实现类有两个一个是真实

spring中自动装配bean

首先用@Component注解类: package soundsystem: import org.springframework.stereotype.Component; @Component public class TestBean{ …… } 开启组件扫描spring才能自动装配bean,创建一个@ComponentScan注解的类 package soundsystem: import org.springframework.context.annotation.componentS

Xcode6中如何修改文件中自动创建的Created by和Copyright

转自: http://blog.csdn.net/bjourney/article/details/46832159 在Xcode6创建问的时候,会自动生成注释 //  Created byxxx on 15/7/10. //  Copyright (c) 2015年 xxxx. All rights reserved. xxx默认为电脑用户名,那么如何修改呢?方法如下: 右键Xcode图标,显示包内容 /Contents/Developer/Library/Xcode/Templates/Fi

Spring中自动装配

自动装配 在我们了解过constructor-arg和property装配中,都需要配置相应的属性和值或者引用,如果在比较复杂的项目中,就会使得XML的配置变得复杂,自动装配可以使用较少的配置实现.主要通过使用bean的autowire属性来控制,autowire可取值: byName:为属性自动装配id与该属性的名字相同的bean 例如:People中有一个名为dog的Dog类 <beanclass="People" id="p" autowire=&quo

Spring中的创建与销毁

在bean中添加属性init-method="方法名" destroy-method="方法名" init-method        该方法是由spring容器执行        在构造函数之后执行        如果在构造函数之后,在调用方法之前要做一些工作,可以在init方法中完成destroy-method        如果该bean是单例,则在spring容器关闭或者销毁的时候,执行该方法        如果该bean是多例,则spring容器不负责销毁

spring中使用动态代理(AOP)

spring是整合了BGLIB和JDK两种动态代理 示例:使用CGLIB代理 public class MyCar { private String color = "blue"; public void run() { System.out.println("我的汽车跑起来了" + color); } } 测试 public class SpringProxy { public static void main(String[] args) { //将代理类的cl