Spring aspect 深度解析

手机游戏开发者 2024-10-4 18:21:12 32 0 来自 中国
先容


  • Spring AOP的实现逻辑在AnnotationAwareAspectJAutoProxyCreator类,AOP的焦点在于Bean对象初始化过程中怎样查找关联的advice并通过创建动态署理。
  • 针对每个Bean在初始化过程中会遍历spring的context上下文查找全部的aop的切面临象,并针对切面临象的每个方法天生一个advisor对象用以匹配每个目标方法。
  • 关于动态署理包罗JdkDynamicAopProxy和ObjenesisCglibAopProxy,后者依靠于cglib的enhancer用法。


AnnotationAwareAspectJAutoProxyCreator

1.png public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport        implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {    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;        }        // 查找该Bean是否有关联的加强类,假如有则创建加强署理        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;    }}

  • wrapIfNecessary方法焦点获取bean是否有干系的加强对象,假如存在加强对象就创建动态署理。
  • 第一个焦点逻辑是查找bean的干系的加强Advisor对象。
  • 第二个焦点逻辑是针对bean和加强对象创建署理对象proxy。


查找加强Advisor

public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport        implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {    @Override    protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) {        // 找到符合要求的Advisors        List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);        if (advisors.isEmpty()) {            return DO_NOT_PROXY;        }        return advisors.toArray();    }    protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {        // 查找候选的candidateAdvisors        List<Advisor> candidateAdvisors = findCandidateAdvisors();        // 在候选的candidateAdvisors中查找可以或许应用到beanClass的Advisors        List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);        extendAdvisors(eligibleAdvisors);        if (!eligibleAdvisors.isEmpty()) {            eligibleAdvisors = sortAdvisors(eligibleAdvisors);        }        return eligibleAdvisors;    }}public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {    @Override    protected List<Advisor> findCandidateAdvisors() {        // Add all the Spring advisors found according to superclass rules.        List<Advisor> advisors = super.findCandidateAdvisors();        // 查找切面 Build Advisors for all AspectJ aspects in the bean factory.        advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());        return advisors;    }}public class BeanFactoryAspectJAdvisorsBuilder {    private final ListableBeanFactory beanFactory;    private final AspectJAdvisorFactory advisorFactory;    private volatile List<String> aspectBeanNames;    private final Map<String, List<Advisor>> advisorsCache = new ConcurrentHashMap<String, List<Advisor>>();    private final Map<String, MetadataAwareAspectInstanceFactory> aspectFactoryCache =            new ConcurrentHashMap<String, MetadataAwareAspectInstanceFactory>();    public List<Advisor> buildAspectJAdvisors() {        List<String> aspectNames = this.aspectBeanNames;        if (aspectNames == null) {            synchronized (this) {                aspectNames = this.aspectBeanNames;                if (aspectNames == null) {                    List<Advisor> advisors = new LinkedList<Advisor>();                    aspectNames = new LinkedList<String>();                    // 查找全部的bean的名称                     String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(                            this.beanFactory, Object.class, true, false);                    // 遍历全部的bean,判断是否是aspect的类                    for (String beanName : beanNames) {                        // 假如是aspect类,必要构建aspect的元数据AspectMetadata                        Class<?> beanType = this.beanFactory.getType(beanName);                        if (this.advisorFactory.isAspect(beanType)) {                            aspectNames.add(beanName);                            AspectMetadata amd = new AspectMetadata(beanType, beanName);                            if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {                                MetadataAwareAspectInstanceFactory factory =                                        new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);                                // 创建Advisor的列表信息,advisorFactory是ReflectiveAspectJAdvisorFactory                                // 获取切面类的加强方法advisor                                List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);                                if (this.beanFactory.isSingleton(beanName)) {                                    this.advisorsCache.put(beanName, classAdvisors);                                }                                else {                                    this.aspectFactoryCache.put(beanName, factory);                                }                                advisors.addAll(classAdvisors);                            }                            else {                                                              MetadataAwareAspectInstanceFactory factory =                                        new PrototypeAspectInstanceFactory(this.beanFactory, beanName);                                this.aspectFactoryCache.put(beanName, factory);                                advisors.addAll(this.advisorFactory.getAdvisors(factory));                            }                        }                    }                    this.aspectBeanNames = aspectNames;                    return advisors;                }            }        }      // 省略干系代码    }}

  • getAdvicesAndAdvisorsForBean调用findEligibleAdvisors查找beanClass对应的加强对象Advisor列表。
  • 查找加强类的焦点逻辑是遍历spring容器内的全部bean对象,假如是aspect切面类则获取Advisor对象。
  • findCandidateAdvisors负责查找全部Advisor对象,内部通过buildAspectJAdvisors查找Advisor对象。
  • buildAspectJAdvisors方法内部的advisorFactory是ReflectiveAspectJAdvisorFactory对象,通过advisorFactory的isAspect判断是否切面类,通过advisorFactory的getAdvisors获取Advisor对象。
  • findAdvisorsThatCanApply负责过滤Advisor对象,过滤和beanClass干系的Advisor列表。
  • Advisor对象是切面类的方法维度的对象,切面类的包罗加强注解的方法都会对应一个Advisor对象。





  • ReflectiveAspectJAdvisorFactory的类继承关系如图所示,焦点关注判断切面类的逻辑。


查找加强Advisor之查找切面类

public abstract class AbstractAspectJAdvisorFactory implements AspectJAdvisorFactory {    private static final String AJC_MAGIC = "ajc$";    private static final Class<?>[] ASPECTJ_ANNOTATION_CLASSES = new Class<?>[] {            Pointcut.class, Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class};    protected final ParameterNameDiscoverer parameterNameDiscoverer = new AspectJAnnotationParameterNameDiscoverer();    @Override    public boolean isAspect(Class<?> clazz) {        return (hasAspectAnnotation(clazz) && !compiledByAjc(clazz));    }    private boolean hasAspectAnnotation(Class<?> clazz) {        return (AnnotationUtils.findAnnotation(clazz, Aspect.class) != null);    }}public abstract class AnnotationUtils {    public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) {        return findAnnotation(clazz, annotationType, true);    }    private static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType, boolean synthesize) {        if (annotationType == null) {            return null;        }        AnnotationCacheKey cacheKey = new AnnotationCacheKey(clazz, annotationType);        A result = (A) findAnnotationCache.get(cacheKey);        if (result == null) {            result = findAnnotation(clazz, annotationType, new HashSet<Annotation>());            if (result != null && synthesize) {                result = synthesizeAnnotation(result, clazz);                findAnnotationCache.put(cacheKey, result);            }        }        return result;    }    private static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType, Set<Annotation> visited) {        try {            Annotation[] anns = clazz.getDeclaredAnnotations();            // 包罗指定的注解            for (Annotation ann : anns) {                if (ann.annotationType() == annotationType) {                    return (A) ann;                }            }            for (Annotation ann : anns) {                if (!isInJavaLangAnnotationPackage(ann) && visited.add(ann)) {                    A annotation = findAnnotation(ann.annotationType(), annotationType, visited);                    if (annotation != null) {                        return annotation;                    }                }            }        }        catch (Throwable ex) {            handleIntrospectionFailure(clazz, ex);            return null;        }        // 省略干系的代码    }}

  • AnnotationUtils的findAnnotation查找是否存在aspect的注解。


查找加强Advisor之获取Advisor

public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFactory implements Serializable {    @Override    public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {        Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();        String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();        validate(aspectClass);        MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =                new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);        List<Advisor> advisors = new ArrayList<Advisor>();        // getAdvisorMethods负责获取AdvisorMethods        for (Method method : getAdvisorMethods(aspectClass)) {             // 获取Advisor            Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);            if (advisor != null) {                advisors.add(advisor);            }        }        if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {            Advisor instantiationAdvisor = new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);            advisors.add(0, instantiationAdvisor);        }        for (Field field : aspectClass.getDeclaredFields()) {            Advisor advisor = getDeclareParentsAdvisor(field);            if (advisor != null) {                advisors.add(advisor);            }        }        return advisors;    }    private List<Method> getAdvisorMethods(Class<?> aspectClass) {        final List<Method> methods = new ArrayList<Method>();        ReflectionUtils.doWithMethods(aspectClass, new ReflectionUtils.MethodCallback() {            @Override            public void doWith(Method method) throws IllegalArgumentException {                // Exclude pointcuts                if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) {                    methods.add(method);                }            }        });        Collections.sort(methods, METHOD_COMPARATOR);        return methods;    }    @Override    public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory,            int declarationOrderInAspect, String aspectName) {        validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());        // 获取 AspectJExpressionPointcut        AspectJExpressionPointcut expressionPointcut = getPointcut(                candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());        if (expressionPointcut == null) {            return null;        }        // 创建Advisor对象InstantiationModelAwarePointcutAdvisorImpl        return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,                this, aspectInstanceFactory, declarationOrderInAspect, aspectName);    }    private AspectJExpressionPointcut getPointcut(Method candidateAdviceMethod, Class<?> candidateAspectClass) {        // 查询对应的方法candidateAdviceMethod是否包罗指定的aspect干系的注解        AspectJAnnotation<?> aspectJAnnotation =                AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);        if (aspectJAnnotation == null) {            return null;        }        // 创建AspectJExpressionPointcut对象        AspectJExpressionPointcut ajexp =                new AspectJExpressionPointcut(candidateAspectClass, new String[0], new Class<?>[0]);        ajexp.setExpression(aspectJAnnotation.getPointcutExpression());        ajexp.setBeanFactory(this.beanFactory);        return ajexp;    }}public abstract class AbstractAspectJAdvisorFactory implements AspectJAdvisorFactory {    private static final String AJC_MAGIC = "ajc$";    private static final Class<?>[] ASPECTJ_ANNOTATION_CLASSES = new Class<?>[] {            Pointcut.class, Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class};    @SuppressWarnings("unchecked")    protected static AspectJAnnotation<?> findAspectJAnnotationOnMethod(Method method) {        for (Class<?> clazz : ASPECTJ_ANNOTATION_CLASSES) {            AspectJAnnotation<?> foundAnnotation = findAnnotation(method, (Class<Annotation>) clazz);            if (foundAnnotation != null) {                return foundAnnotation;            }        }        return null;    }}

  • getAdvisorMethods负责从切面类aspectClass获取干系的Method。
  • getAdvisor负责将包罗aspct注解的Method转换成Advisor对象。
  • findAspectJAnnotationOnMethod判断方法是否包罗aspect注解如Around.class等
  • 切面类aspectClass的每个包罗aspect的注解method会天生AspectJExpressionPointcut对象,进而天生InstantiationModelAwarePointcutAdvisorImpl对象。
  • 切面类包罗aspect注解的method会天生Advisor对象,即InstantiationModelAwarePointcutAdvisorImpl对象





  • Advisor对象是InstantiationModelAwarePointcutAdvisorImpl对象。


查找加强Advisor之过滤Advisor

public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {    private BeanFactoryAdvisorRetrievalHelper advisorRetrievalHelper;    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 abstract class AopUtils {    public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {        if (candidateAdvisors.isEmpty()) {            return candidateAdvisors;        }        List<Advisor> eligibleAdvisors = new LinkedList<Advisor>();        // 遍历全部的Advisor举行匹配返回符合的Advisor        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) {        return canApply(advisor, targetClass, false);    }    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 {            return true;        }    }    public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {        if (!pc.getClassFilter().matches(targetClass)) {            return false;        }        MethodMatcher methodMatcher = pc.getMethodMatcher();        if (methodMatcher == MethodMatcher.TRUE) {            return true;        }        IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;        if (methodMatcher instanceof IntroductionAwareMethodMatcher) {            introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;        }        Set<Class<?>> classes = new LinkedHashSet<Class<?>>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));        classes.add(targetClass);        for (Class<?> clazz : classes) {            // 获取类下面的全部Method对象            Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);            for (Method method : methods) {                if ((introductionAwareMethodMatcher != null &&                        introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||                      // methodMatcher包罗AspectJExpressionPointcut                        methodMatcher.matches(method, targetClass)) {                    return true;                }            }        }        return false;    }}

  • findAdvisorsThatCanApply查找匹配的Advisors。
  • findAdvisorsThatCanApply的条件是目标类的某个方法和Advisor匹配,只要目标类的某个方法和Advisor匹配上就表明该Advisor符合条件。


创建署理流程

AbstractAutoProxyCreator

public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport        implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {    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);            }        }                // 将拦截器Interceptors封装成加强器advisors        Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);                // 参加加强器        proxyFactory.addAdvisors(advisors);        proxyFactory.setTargetSource(targetSource);                // 定制署理        customizeProxyFactory(proxyFactory);        proxyFactory.setFrozen(this.freezeProxy);        if (advisorsPreFiltered()) {            proxyFactory.setPreFiltered(true);        }                // 封装出proxyFactory并由它完成后续的工作        return proxyFactory.getProxy(getProxyClassLoader());    }}

  • ProxyFactory负责天生动态署理的Proxy对象。
  • ProxyFactory设置了署理对象targetSource和拦截器对象advisors。
  • ProxyFactory通过getProxy来天生动态署理的Proxy对象。


ProxyFactory

public class ProxyFactory extends ProxyCreatorSupport {    public Object getProxy(ClassLoader classLoader) {        // createAopProxy创建动态署理实现对象        // getProxy负责创建动态署理        return createAopProxy().getProxy(classLoader);    }}public class ProxyCreatorSupport extends AdvisedSupport {    protected final synchronized AopProxy createAopProxy() {        if (!this.active) {            activate();        }        // 这里我们必要注意的是 ,这里 createAopProxy 传入的是 this。也就是说这里参数通报实际上是ProxyFactroy        return getAopProxyFactory().createAopProxy(this);    }}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);        }    }}

  • createAopProxy会根据是否实现Interface来选用cglib还是jdk的动态署理。
  • ObjenesisCglibAopProxy是cglib情势的动态署理。
  • JdkDynamicAopProxy是jdk情势的动态署理。


CglibAopProxy

class CglibAopProxy implements AopProxy, Serializable {    @Override    public Object getProxy(ClassLoader classLoader) {        try {                        // 获取署理类,rootClass体现的是被署理类            Class<?> rootClass = this.advised.getTargetClass();            Class<?> proxySuperClass = rootClass;            if (ClassUtils.isCglibProxyClass(rootClass)) {                proxySuperClass = rootClass.getSuperclass();                Class<?>[] additionalInterfaces = rootClass.getInterfaces();                for (Class<?> additionalInterface : additionalInterfaces) {                    this.advised.addInterface(additionalInterface);                }            }            validateClassIfNecessary(proxySuperClass, classLoader);            // 设置 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();            }            enhancer.setCallbackFilter(new ProxyCallbackFilter(                    this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));            enhancer.setCallbackTypes(types);            // 创建署理对象            return createProxyClassAndInstance(enhancer, callbacks);        }        catch (CodeGenerationException ex) {        }        catch (IllegalArgumentException ex) {        }        catch (Throwable ex) {        }    }    protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {        enhancer.setInterceptDuringConstruction(false);        enhancer.setCallbacks(callbacks);        return (this.constructorArgs != null ?                enhancer.create(this.constructorArgTypes, this.constructorArgs) :                enhancer.create());    }}

  • CglibAopProxy的焦点通过Enhancer实现动态署理的创建。
  • Enhancer的焦点变量superclass代表被署理对象类,callbacks代表拦截器,callbackFilter代表callback的匹配过滤器。


Callback

class CglibAopProxy implements AopProxy, Serializable {    private Callback[] getCallbacks(Class<?> rootClass) throws Exception {        boolean exposeProxy = this.advised.isExposeProxy();        boolean isFrozen = this.advised.isFrozen();        boolean isStatic = this.advised.getTargetSource().isStatic();        Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);        Callback targetInterceptor;        if (exposeProxy) {            targetInterceptor = (isStatic ?                    new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :                    new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()));        }        else {            targetInterceptor = (isStatic ?                    new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :                    new DynamicUnadvisedInterceptor(this.advised.getTargetSource()));        }        Callback targetDispatcher = (isStatic ?                new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp());        // 回调聚集。此中包罗aopInterceptor 中包罗了 Aspect 的加强        //  advisedDispatcher 用于判断假如method是Advised.class声明的,则使用AdvisedDispatcher举行分发        Callback[] mainCallbacks = new Callback[] {                aopInterceptor,                  targetInterceptor,                  new SerializableNoOp(),                  targetDispatcher, this.advisedDispatcher,                new EqualsInterceptor(this.advised),                new HashCodeInterceptor(this.advised)        };        Callback[] callbacks;        if (isStatic && isFrozen) {                // 省略干系的代码        }        else {            callbacks = mainCallbacks;        }        return callbacks;    }}

  • mainCallbacks包罗了全部的拦截器,期中aopInterceptor是焦点的aspect干系的拦截器对象。
  • aopInterceptor是DynamicAdvisedInterceptor对象,是实验aop拦截的焦点。


DynamicAdvisedInterceptor

class CglibAopProxy implements AopProxy, Serializable {    private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable {        private final AdvisedSupport advised;        public DynamicAdvisedInterceptor(AdvisedSupport advised) {            this.advised = advised;        }        @Override        public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {            Object oldProxy = null;            boolean setProxyContext = false;            Class<?> targetClass = null;            Object target = null;            try {                if (this.advised.exposeProxy) {                    oldProxy = AopContext.setCurrentProxy(proxy);                    setProxyContext = true;                }                target = getTarget();                if (target != null) {                    targetClass = target.getClass();                }                List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);                Object retVal;                if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {                    Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);                    retVal = methodProxy.invoke(target, argsToUse);                }                else {                    retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();                }                retVal = processReturnType(proxy, target, method, retVal);                return retVal;            }            finally {                if (target != null) {                    releaseTarget(target);                }                if (setProxyContext) {                    AopContext.setCurrentProxy(oldProxy);                }            }        }    }}

  • DynamicAdvisedInterceptor#intercept通过getInterceptorsAndDynamicInterceptionAdvice查找被调用method关联的拦截器,拦截器不为空则创建CglibMethodInvocation实验署理过程。


callbackFilter

class CglibAopProxy implements AopProxy, Serializable {    private static final int AOP_PROXY = 0;    private static final int INVOKE_TARGET = 1;    private static final int NO_OVERRIDE = 2;    private static final int DISPATCH_TARGET = 3;    private static final int DISPATCH_ADVISED = 4;    private static final int INVOKE_EQUALS = 5;    private static final int INVOKE_HASHCODE = 6;    private static class ProxyCallbackFilter implements CallbackFilter {        private final AdvisedSupport advised;        private final Map<String, Integer> fixedInterceptorMap;        private final int fixedInterceptorOffset;        public ProxyCallbackFilter(AdvisedSupport advised, Map<String, Integer> fixedInterceptorMap, int fixedInterceptorOffset) {            this.advised = advised;            this.fixedInterceptorMap = fixedInterceptorMap;            this.fixedInterceptorOffset = fixedInterceptorOffset;        }        @Override        public int accept(Method method) {            if (AopUtils.isFinalizeMethod(method)) {                return NO_OVERRIDE;            }            if (!this.advised.isOpaque() && method.getDeclaringClass().isInterface() &&            method.getDeclaringClass().isAssignableFrom(Advised.class)) {                return DISPATCH_ADVISED;            }            if (AopUtils.isEqualsMethod(method)) {                return INVOKE_EQUALS;            }            if (AopUtils.isHashCodeMethod(method)) {                return INVOKE_HASHCODE;            }            Class<?> targetClass = this.advised.getTargetClass();            List<?> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);            boolean haveAdvice = !chain.isEmpty();            boolean exposeProxy = this.advised.isExposeProxy();            boolean isStatic = this.advised.getTargetSource().isStatic();            boolean isFrozen = this.advised.isFrozen();            if (haveAdvice || !isFrozen) {                if (exposeProxy) {                    return AOP_PROXY;                }                String key = method.toString();                if (isStatic && isFrozen && this.fixedInterceptorMap.containsKey(key)) {                    int index = this.fixedInterceptorMap.get(key);                    return (index + this.fixedInterceptorOffset);                }                else {                    return AOP_PROXY;                }            }            else {                if (exposeProxy || !isStatic) {                    return INVOKE_TARGET;                }                Class<?> returnType = method.getReturnType();                if (returnType.isAssignableFrom(targetClass)) {                    return INVOKE_TARGET;                }                else {                    return DISPATCH_TARGET;                }            }        }}

  • callbackFilter#accept的在CglibAopProxy调用过程中被实验,假如匹配存在拦截器就返回AOP_PROXY实验aopInterceptor。
  • advised.getInterceptorsAndDynamicInterceptionAdvice负责匹配当前被调用的method的拦截器。


DefaultAdvisorChainFactory

public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable {    @Override    public List<Object> getInterceptorsAndDynamicInterceptionAdvice(            Advised config, Method method, Class<?> targetClass) {        List<Object> interceptorList = new ArrayList<Object>(config.getAdvisors().length);        Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());        boolean hasIntroductions = hasMatchingIntroductions(config, actualClass);        AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();        for (Advisor advisor : config.getAdvisors()) {            if (advisor instanceof PointcutAdvisor) {                PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;                if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {                    MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();                    if (MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) {                        MethodInterceptor[] interceptors = registry.getInterceptors(advisor);                        if (mm.isRuntime()) {                            for (MethodInterceptor interceptor : interceptors) {                                interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));                            }                        }                        else {                            interceptorList.addAll(Arrays.asList(interceptors));                        }                    }                }            }            else if (advisor instanceof IntroductionAdvisor) {                IntroductionAdvisor ia = (IntroductionAdvisor) advisor;                if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {                    Interceptor[] interceptors = registry.getInterceptors(advisor);                    interceptorList.addAll(Arrays.asList(interceptors));                }            }            else {                Interceptor[] interceptors = registry.getInterceptors(advisor);                interceptorList.addAll(Arrays.asList(interceptors));            }        }        return interceptorList;    }    private static boolean hasMatchingIntroductions(Advised config, Class<?> actualClass) {        for (Advisor advisor : config.getAdvisors()) {            if (advisor instanceof IntroductionAdvisor) {                IntroductionAdvisor ia = (IntroductionAdvisor) advisor;                if (ia.getClassFilter().matches(actualClass)) {                    return true;                }            }        }        return false;    }}

  • getInterceptorsAndDynamicInterceptionAdvice遍历全部的拦截器,根据类和方法举行过滤后返回匹配的拦截器。


CglibMethodInvocation

class CglibAopProxy implements AopProxy, Serializable {    private static class CglibMethodInvocation extends ReflectiveMethodInvocation {        private final MethodProxy methodProxy;        private final boolean publicMethod;        public CglibMethodInvocation(Object proxy, Object target, Method method, Object[] arguments,                Class<?> targetClass, List<Object> interceptorsAndDynamicMethodMatchers, MethodProxy methodProxy) {            super(proxy, target, method, arguments, targetClass, interceptorsAndDynamicMethodMatchers);            this.methodProxy = methodProxy;            this.publicMethod = Modifier.isPublic(method.getModifiers());        }        @Override        protected Object invokeJoinpoint() throws Throwable {            if (this.publicMethod) {                return this.methodProxy.invoke(this.target, this.arguments);            }            else {                return super.invokeJoinpoint();            }        }    }}public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {    protected final Object proxy;    protected final Object target;    protected final Method method;    protected Object[] arguments;    private final Class<?> targetClass;    private Map<String, Object> userAttributes;    protected final List<?> interceptorsAndDynamicMethodMatchers;    private int currentInterceptorIndex = -1;    protected ReflectiveMethodInvocation(            Object proxy, Object target, Method method, Object[] arguments,            Class<?> targetClass, List<Object> interceptorsAndDynamicMethodMatchers) {        this.proxy = proxy;        this.target = target;        this.targetClass = targetClass;        this.method = BridgeMethodResolver.findBridgedMethod(method);        this.arguments = AopProxyUtils.adaptArgumentsIfNecessary(method, arguments);        this.interceptorsAndDynamicMethodMatchers = interceptorsAndDynamicMethodMatchers;    }    @Override    public Object proceed() throws Throwable {        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {                        // 实验CglibMethodInvocation的invokeJoinpoint方法            return invokeJoinpoint();        }        Object interceptorOrInterceptionAdvice =                this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);        if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {            InterceptorAndDynamicMethodMatcher dm =                    (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;            if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {                return dm.interceptor.invoke(this);            }            else {                return proceed();            }        }        else {            return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);        }    }}

  • ReflectiveMethodInvocation负责先实验拦截器,末了调用实验被调用的方法。
  • CglibMethodInvocation#invokeJoinpoint方法实验被署理方法。


参考


  • 解析AOP源码,从解析设置开始
  • 解析AOP焦点源码,如安在创建bean时找寻切面Aspect并天生署理类
  • Spring源码分析十三:@Aspect方式的AOP下篇 - createProxy
  • Spring源码分析二十四:cglib 的署理过程
  • aop官方文档
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 16:46, Processed in 0.212886 second(s), 35 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表