Spring注解驱动之@EnableAspectJAutoProxy注解

导读:本篇文章讲解 Spring注解驱动之@EnableAspectJAutoProxy注解,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

概述

EnableAspectJAutoProxy注解

在配置类上添加@EnableAspectJAutoProxy注解,便能够开启注解版的AOP功能。也就是说,如果要使注解版的AOP功能起作用的话,那么就得需要在配置类上添加@EnableAspectJAutoProxy注解。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({AspectJAutoProxyRegistrar.class})
public @interface EnableAspectJAutoProxy {
    boolean proxyTargetClass() default false;
    boolean exposeProxy() default false;
}

从源码可以看出,@EnableAspectJAutoProxy注解使用@Import注解给容器中引入了AspectJAutoProxyRegister组件。

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
    AspectJAutoProxyRegistrar() {
    }

    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
        AnnotationAttributes enableAspectJAutoProxy = AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
        if (enableAspectJAutoProxy != null) {
            if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
                AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
            }

            if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
                AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
            }
        }
    }
}

可以看到AspectJAutoProxyRegistrar类实现了ImportBeanDefinitionRegistrar接口。
我知道实现这个接口是为了手动向容器中导入bean对象。
参考:《Spring注解驱动开发第10讲——在@Import注解中使用ImportBeanDefinitionRegistrar向容器中注册bean》
这篇文章中介绍过,通过ImportBeanDefinitionRegistrar接口实现将自定义的组件添加到IOC容器中。
也就是说,@EnableAspectJAutoProxy注解使用AspectJAutoProxyRegistrar对象自定义组件,并将相应的组件添加到IOC容器中。
那么,@EnableAspectJAutoProxy注解使用AspectJAutoProxyRegistrar对象向容器中注册了一个什么bean呢?

调试Spring源码

源码比较简单,大家手动调试一下就可以了。

总结

综上所述,在Spring的配置类上添加@EnableAspectJAutoProxy注解后,会向容器中注册AnnotationAwareAspectJAutoProxyCreator,翻译过来就叫注解装配模式的AspectJ切面自动代理创建器。
其实只要把AnnotationAwareAspectJAutoProxyCreator弄清楚了,就彻底理解了AOP的原理。

参考

Spring注解驱动开发第26讲——总有人让我给他讲讲@EnableAspectJAutoProxy注解

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/99986.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!