深入Spring:自定义AOP

前言

上一篇文章讲了如何自定义IOC。这篇讲一下Spring的AOP过程,介绍一下Spring对Advisor的加载和使用,并通过自定义Aspect和Advisor,实现简单的Aop功能。

Spring Aop

Spring开启AOP一般是使用@EnableAspectJAutoProxy来开启的。这个注解的主要作用是注入了一个实现了BeanPostProcessor接口的类。这个接口在前面介绍过,会嵌入到Bean的实例化过程。
所以只要我们注入这个类AnnotationAwareAspectJAutoProxyCreator也可以开启AOP功能了。完整的代码放在Github上。

    @Bean
    public AnnotationAwareAspectJAutoProxyCreator makeAnnotationAwareAspectJAutoProxyCreator() {
        return new AnnotationAwareAspectJAutoProxyCreator();
    }

调试AnnotationAwareAspectJAutoProxyCreator的源码会发现,这个类继承的AbstractAutoProxyCreator的方法postProcessAfterInitialization中对符合切片的bean进行了二次代理,具体的代码如下。

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean != null) {
            Object cacheKey = getCacheKey(bean.getClass(), beanName);
            if (!this.earlyProxyReferences.containsKey(cacheKey)) {
                return wrapIfNecessary(bean, beanName, cacheKey);
            }
        }
        return bean;
    }
    protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
        if (beanName != null && this.targetSourcedBeans.containsKey(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;
        }
        // Create proxy if we have advice.
        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;
    }

Aspect是通过BeanFactoryAspectJAdvisorsBuilderbuildAspectJAdvisors方法加载的。这个方法会读取bean的切片信息,并生成Advisor的列表,同时存在advisorsCache里面。

    public List<Advisor> buildAspectJAdvisors() {
        List<String> aspectNames = null;
        synchronized (this) {
            aspectNames = this.aspectBeanNames;
            if (aspectNames == null) {
                List<Advisor> advisors = new LinkedList<Advisor>();
                aspectNames = new LinkedList<String>();
                String[] beanNames =
                        BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Object.class, true, false);
                for (String beanName : beanNames) {
                    if (!isEligibleBean(beanName)) {
                        continue;
                    }
                    // We must be careful not to instantiate beans eagerly as in this
                    // case they would be cached by the Spring container but would not
                    // have been weaved
                    Class beanType = this.beanFactory.getType(beanName);
                    if (beanType == null) {
                        continue;
                    }
                    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);
                            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 {
                            // Per target or per this.
                            if (this.beanFactory.isSingleton(beanName)) {
                                throw new IllegalArgumentException("Bean with name '" + beanName +
                                        "' is a singleton, but aspect instantiation model is not singleton");
                            }
                            MetadataAwareAspectInstanceFactory factory =
                                    new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
                            this.aspectFactoryCache.put(beanName, factory);
                            advisors.addAll(this.advisorFactory.getAdvisors(factory));
                        }
                    }
                }
                this.aspectBeanNames = aspectNames;
                return advisors;
            }
        }
        if (aspectNames.isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        List<Advisor> advisors = new LinkedList<Advisor>();
        for (String aspectName : aspectNames) {
            List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);
            if (cachedAdvisors != null) {
                advisors.addAll(cachedAdvisors);
            }
            else {
                MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);
                advisors.addAll(this.advisorFactory.getAdvisors(factory));
            }
        }
        return advisors;
    }

使用的时候,Spring会根据pointCut选择合适的Advisor对相应的Bean做代理。

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

二次代理的Bean在执行的过程中是使用ReflectiveMethodInvocationproceed方法来执行Advisor的处理逻辑的。
上一步选出来的Advisor存在interceptorsAndDynamicMethodMatchers属性里,这是一个Advisor的列表,所以执行的过程中采用了责任链模式,不同的Advisor会依次调用下一个Advisor。

    public Object proceed() throws Throwable {
        //  We start with an index of -1 and increment early.
        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
            return invokeJoinpoint();
        }
        Object interceptorOrInterceptionAdvice =
                this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
        if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
            // Evaluate dynamic method matcher here: static part will already have
            // been evaluated and found to match.
            InterceptorAndDynamicMethodMatcher dm =
                    (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
            if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
                return dm.interceptor.invoke(this);
            }
            else {
                // Dynamic matching failed.
                // Skip this interceptor and invoke the next in the chain.
                return proceed();
            }
        }
        else {
            // It's an interceptor, so we just invoke it: The pointcut will have
            // been evaluated statically before this object was constructed.
            return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
        }
    }

这条责任链里包含了Advisor的处理顺序,通过程序的流程图能能明显的表示出来,为了完整描述,这里假设是完整的Advisor。


SpringAop.png

从图中可以完整的看出来各个Advisor的执行顺序。

自定义AOP

所以自定义AOP也是相同的思路,通过继承BeanPostProcessor来二次代理bean,完整的代码放在Github上了。
为了简便起见,只定义了一个注解@MyAspect,具体的Advisor通过函数名控制。
先看注解的定义,加上Component使Spring可以识别这个注解,并加载,pointCut属性则是定义切片。

@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface MyAspect {
    String value() default "";
    String pointCut();
}

再看具体的使用上,pointCut定义了切片,然后定义了beforeafteraround,这三个方法,目前只实现了这三个具有代表性的Advisor。

@Configuration
public class CustomizeAspectTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(CustomizeAspectTest.class);
        annotationConfigApplicationContext.refresh();
        Test test = annotationConfigApplicationContext.getBean(Test.class);
        test.test();
    }
    @Component
    public static class Test {
        public void test() {
            System.out.println("hello world");
        }
    }
    @MyAspect(pointCut = "org.wcong.test.spring.aop.CustomizeAspectTest.Test.test")
    public static class MyAspectClass {
        void before(Object[] args) {
            System.out.println("aop before");
        }
        void after(Object[] args) {
            System.out.println("aop after");
        }
        void around(MethodInvocation methodInvocation, Object[] args) throws Throwable {
            System.out.println("aop around before");
            methodInvocation.proceed(methodInvocation);
            System.out.println("aop around after");
        }
    }
    @Bean
    public CustomizeAspectProxy getCustomizeAspectScan() {
        return new CustomizeAspectProxy();
    }
}

可以发现最后导出了一个CustomizeAspectProxy的类,这个就是自定义Aop的切入点了。这里面主要实现了Advisor的加载,和对符合切片的Bean的二次代理。

public class CustomizeAspectProxy implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;
    private List<AbstractAdvisor> advisorList;
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        buildAdvisor();
        Map<Method, List<AbstractAdvisor>> matchAdvisorMap = matchAdvisor(bean);
        if (matchAdvisorMap.isEmpty()) {
            return bean;
        } else {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(bean.getClass());
            enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
            enhancer.setCallback(new MethodInterceptorImpl(matchAdvisorMap));
            return enhancer.create();
        }
    }
    private Map<Method, List<AbstractAdvisor>> matchAdvisor(Object bean) {
        Class<?> beanClass = bean.getClass();
        Method[] methods = beanClass.getMethods();
        if (methods == null) {
            return Collections.emptyMap();
        }
        Map<Method, List<AbstractAdvisor>> methodListMap = new HashMap<Method, List<AbstractAdvisor>>();
        for (Method method : methods) {
            for (AbstractAdvisor abstractAdvisor : advisorList) {
                if (!abstractAdvisor.isMatch(bean.getClass(), method)) {
                    continue;
                }
                List<AbstractAdvisor> advisorList = methodListMap.get(method);
                if (advisorList == null) {
                    advisorList = new LinkedList<AbstractAdvisor>();
                    methodListMap.put(method, advisorList);
                }
                advisorList.add(abstractAdvisor);
            }
        }
        return methodListMap;
    }
    private void buildAdvisor() {
        if (advisorList != null) {
            return;
        }
        synchronized (this) {
            if (advisorList != null) {
                return;
            }
            String[] beanNames = applicationContext.getBeanDefinitionNames();
            advisorList = new ArrayList<AbstractAdvisor>();
            for (String beanName : beanNames) {
                Class<?> beanClass = applicationContext.getType(beanName);
                MyAspect myAspect = beanClass.getAnnotation(MyAspect.class);
                if (myAspect == null) {
                    continue;
                }
                Method[] methods = beanClass.getDeclaredMethods();
                if (methods == null) {
                    continue;
                }
                Object bean = applicationContext.getBean(beanName);
                List<AbstractAdvisor> beanAdvisorList = new ArrayList<AbstractAdvisor>(methods.length);
                for (Method method : methods) {
                    if (method.getName().equals("before")) {
                        beanAdvisorList.add(new MethodInvocation.BeforeAdvisor(bean, method));
                    } else if (method.getName().equals("around")) {
                        beanAdvisorList.add(new MethodInvocation.AroundAdvisor(bean, method));
                    } else if (method.getName().equals("after")) {
                        beanAdvisorList.add(new MethodInvocation.AfterAdvisor(bean, method));
                    }
                }
                advisorList.addAll(beanAdvisorList);
            }
            Collections.sort(advisorList, new Comparator<AbstractAdvisor>() {
                public int compare(AbstractAdvisor o1, AbstractAdvisor o2) {
                    return o1.getOrder() - o2.getOrder();
                }
            });
        }
    }
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

其中buildAdvisor是从applicationContext里面取出所有的bean选出有MyAspect注解的类,解析成Advisor,注意到后面有一个排序,是因为这个责任链是有顺序的,after>around>before。
matchAdvisor则是读取类的信息,判断需要被代理,然后返回每个方法被代理的advisorList。
接下来是实现代理的类了,这个类是cglib的一个简单的判断,发现相应的函数有Advisor,走Aop模式,没有,走普通的代理模式。

public class MethodInterceptorImpl implements MethodInterceptor {
    private Map<Method, List<AbstractAdvisor>> advisorMap;
    public MethodInterceptorImpl(Map<Method, List<AbstractAdvisor>> advisorMap) {
        this.advisorMap = advisorMap;
    }
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        List<AbstractAdvisor> advisorList = advisorMap.get(method);
        if (advisorList == null) {
            return methodProxy.invokeSuper(o, objects);
        } else {
            MethodInvocation methodInvocation = new MethodInvocation(o, method, objects, methodProxy, advisorList);
            return methodInvocation.proceed(methodInvocation);
        }
    }
}

MethodInvocation就是具体的责任链实现的Advisor的逻辑了。MethodInvocation包含了具体需要代理的方法的元数据,并在proceed方法中开启方法的执行链路,依次调用。而这条责任链的处理链路就是after->around->before->methodProxy->around->after。

public interface Proceed {   
  Object proceed(MethodInvocation methodInvocation) throws Throwable;
}
public class MethodInvocation implements Proceed {
    private List<AbstractAdvisor> advisorList;
    private Object sourceObject;
    private Method sourceMethod;
    private Object[] sourceParameters;
    private MethodProxy sourceMethodProxy;
    private int advisorIndex = -1;
    public MethodInvocation(Object o, Method method, Object[] objects, MethodProxy methodProxy,
            List<AbstractAdvisor> advisorList) {
        this.sourceObject = o;
        this.sourceMethod = method;
        this.sourceParameters = objects;
        this.sourceMethodProxy = methodProxy;
        this.advisorList = advisorList;
    }
    public Object proceed(MethodInvocation methodInvocation) throws Throwable {
        if (advisorIndex == advisorList.size() - 1) {
            return sourceMethodProxy.invokeSuper(sourceObject, sourceParameters);
        } else {
            advisorIndex += 1;
            return advisorList.get(advisorIndex).proceed(this);
        }
    }
    public static class AroundAdvisor extends AbstractAdvisor {
        public AroundAdvisor(Object aspectObject, Method aspectMethod) {
            super(aspectObject, aspectMethod);
            order = AbstractAdvisor.AROUND_ORDER;
        }
        public Object proceed(MethodInvocation methodInvocation) throws Throwable {
            Object[] param = { methodInvocation, methodInvocation.sourceParameters };
            return aspectMethod.invoke(aspectObject, param);
        }
    }
    public static class BeforeAdvisor extends AbstractAdvisor {
        public BeforeAdvisor(Object aspectObject, Method aspectMethod) {
            super(aspectObject, aspectMethod);
            order = AbstractAdvisor.BEFORE_ORDER;
        }
        public Object proceed(MethodInvocation methodInvocation) throws Throwable {
            Object[] param = { methodInvocation.sourceParameters };
            aspectMethod.invoke(aspectObject, param);
            return methodInvocation.proceed(methodInvocation);
        }
    }
    public static class AfterAdvisor extends AbstractAdvisor {
        public AfterAdvisor(Object aspectObject, Method aspectMethod) {
            super(aspectObject, aspectMethod);
            order = AbstractAdvisor.AFTER_ORDER;
        }
        public Object proceed(MethodInvocation methodInvocation) throws Throwable {
            methodInvocation.proceed(methodInvocation);
            Object[] param = { methodInvocation.sourceParameters };
            return aspectMethod.invoke(aspectObject, param);
        }
    }
}

结语

Spring Aop的实现主要是bean的二次代理,还是用到了BeanPostProcessor,来嵌入实现的。同时依赖了Aspectj的相关定义,通过Advisor的责任链来实现嵌入到bean方法的执行前后。同时也跟Aspectj高度耦合,会直接使用Aspectj的很多类,就很难实现定制化了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,530评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,403评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,120评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,770评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,758评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,649评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,021评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,675评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,931评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,751评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,410评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,004评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,969评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,042评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,493评论 2 343

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,594评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,733评论 6 342
  • 什么是Spring Spring是一个开源的Java EE开发框架。Spring框架的核心功能可以应用在任何Jav...
    jemmm阅读 16,438评论 1 133
  • 本博中关于spring的文章:Spring IOC和AOP原理,Spring事务原理探究,Spring配置文件属性...
    Maggie编程去阅读 4,095评论 0 34
  • 正则表达式必知必会 匹配单个字符 匹配纯文本 相当于文本查找的功能(CMD + F)。但是一般的正则表达式引擎默认...
    三十一_iOS阅读 1,077评论 0 1