Spring Aop自动创建代理

1.介绍


在Bean生命周期过长中调用BeanPostProcessor,将对象进行包装,生成代理对象。

2.举例


public class LogMethodInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        String methodName = invocation.getMethod().getName();
        invocation.processed();
    }
}

@Configuration
public class LogConfiguration extends AbstractPointcutAdvisor {

    private Pointcut pointcut;

    private Advice advice;

    @PostConstruct
    public void init() {

        this.pointcut = new AnnotationMatchingPointcut(null,Log.class);
        this.advice = new LogMethodInterceptor();
    }

    @Override
    public Pointcut getPointcut() {
        return this.pointcut;
    }

    @Override
    public Advice getAdvice() {
        return this.advice;
    }

}

3.DefaultAdvisorAutoProxyCreator 源码分析

public class DefaultAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator implements BeanNameAware {
}

DefaultAdvisorAutoProxyCreator 继承
AbstractAdvisorAutoProxyCreator。主要对Advisor类型的bean修改名称。实现BeanNameAware接口。

3.1 AbstractAdvisorAutoProxyCreator 源码分析

public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
}

此抽象类继承 AbstractAutoProxyCreator

关键代码源码分析:
查找所有实现Advisor的bean。存放到集合中。

protected List findCandidateAdvisors() {
    Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
    return this.advisorRetrievalHelper.findAdvisorBeans();
}

public List findAdvisorBeans() {
    //获取所有的advisor name。如果缓存不在创建
    String[] advisorNames = null;
    synchronized (this) {
        advisorNames = this.cachedAdvisorBeanNames;
        if (advisorNames == null) {
            //查找所有实现Advisor接口的类
            advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                    this.beanFactory, Advisor.class, true, false);
            this.cachedAdvisorBeanNames = advisorNames;
        }
    }
    if (advisorNames.length == 0) {
        return new LinkedList<>();
    }

    List advisors = new LinkedList<>();
    for (String name : advisorNames) {
        //依据bean name判断是否是想要的advisor
        if (isEligibleBean(name)) {
            if (this.beanFactory.isCurrentlyInCreation(name)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Skipping currently created advisor '" + name + "'");
                }
            }
            else {
                try {
                   //依据bean name创建创建bean
                    advisors.add(this.beanFactory.getBean(name, Advisor.class));
                }
                catch (BeanCreationException ex) {
                    //....
                    throw ex;
                }
            }
        }
    }
    return advisors;
}

获取能满足当前类advisor集合

@Override
@Nullable
protected Object[] getAdvicesAndAdvisorsForBean(
        Class beanClass, String beanName, @Nullable TargetSource targetSource) {
    //获取能满足当前类advisor集合
    List advisors = findEligibleAdvisors(beanClass, beanName);
    if (advisors.isEmpty()) {
        return DO_NOT_PROXY;
    }
    return advisors.toArray();
}

protected List findEligibleAdvisors(Class beanClass, String beanName) {
    List candidateAdvisors = findCandidateAdvisors();
    List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
    extendAdvisors(eligibleAdvisors);
    if (!eligibleAdvisors.isEmpty()) {
        eligibleAdvisors = sortAdvisors(eligibleAdvisors);
    }
    return eligibleAdvisors;
}

/**
*搜索所有的能应用于当前bean的Advisor
*/
protected List findAdvisorsThatCanApply(
            List candidateAdvisors, Class beanClass, String beanName) {

    ProxyCreationContext.setCurrentProxiedBeanName(beanName);
    try {
        return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
    }
    finally {
        ProxyCreationContext.setCurrentProxiedBeanName(null);
    }
}

public static List findAdvisorsThatCanApply(List candidateAdvisors, Class clazz) {
    if (candidateAdvisors.isEmpty()) {
        return candidateAdvisors;
    }
    //合适
    List eligibleAdvisors = new LinkedList<>();
    for (Advisor candidate : candidateAdvisors) {
        if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
            eligibleAdvisors.add(candidate);
        }
    }
    boolean hasIntroductions = !eligibleAdvisors.isEmpty();
    for (Advisor candidate : candidateAdvisors) {
        if (candidate instanceof IntroductionAdvisor) {
            // already processed
            continue;
        }
        if (canApply(candidate, clazz, hasIntroductions)) {
            eligibleAdvisors.add(candidate);
        }
    }
    return eligibleAdvisors;
}

public static boolean canApply(Advisor advisor, Class targetClass, boolean hasIntroductions) {
    if (advisor instanceof IntroductionAdvisor) {
        return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
    }
    else if (advisor instanceof PointcutAdvisor) {
        PointcutAdvisor pca = (PointcutAdvisor) advisor;
        return canApply(pca.getPointcut(), targetClass, hasIntroductions);
    }
    else {
        // It doesn't have a pointcut so we assume it applies.
        return true;
    }
}

你可能感兴趣的:(spring)