在SpringBoot开发过程,我们经常会遇到@Enable开始的好多注解,比如@EnableEurekaServer、@EnableAsync、@EnableScheduling等,今天我们就来分析下这些注解到底是如何工作的?

本文目录

一、@Enable*实现的原理二、@Import注解的用法1. 直接导入配置类2. 依据条件选择配置类3. 动态注册Bean

一、@Enable*实现的原理

通过这些@Enable*注解的源码可以看出,所有@Enable*注解里面都有一个@Import注解,而@Import是用来导入配置类的,所以@Enable*自动开启的实现原理其实就是导入了一些自动配置的Bean。

二、@Import注解的用法

@Import注解允许导入@Configuration类,ImportSelector和ImportBeanDefinitionRegistrar的实现类,等同于正常的组件类。

有以下三种使用方式

1. 直接导入配置类

@EnableEurekaServer使用了这种方式,注解源码如下:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({EurekaServerMarkerConfiguration.class})
public @interface EnableEurekaServer {
}

可以看到@EnableEurekaServer注解直接导入了配置类EurekaServerMarkerConfiguration,而这个配置类中向spring容器中注册了一个EurekaServerMarkerConfiguration的Bean。

EurekaServerMarkerConfiguration的源码如下:

@Configuration
public class EurekaServerMarkerConfiguration {
    public EurekaServerMarkerConfiguration() {
    }     @Bean
    public EurekaServerMarkerConfiguration.Marker eurekaServerMarkerBean() {
        return new EurekaServerMarkerConfiguration.Marker();
    }     class Marker {
        Marker() {
        }
    }
}

2. 依据条件选择配置类

@EnableAsync使用了这种方式,注解源码如下:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AsyncConfigurationSelector.class)
public @interface EnableAsync {     Class<? extends Annotation> annotation() default Annotation.class;     boolean proxyTargetClass() default false;     AdviceMode mode() default AdviceMode.PROXY;     int order() default Ordered.LOWEST_PRECEDENCE;
}

EnableAsync注解中导入了AsyncConfigurationSelector,AsyncConfigurationSelector通过条件来选择需要导入的配置类,继承AdviceModeImportSelector又实现了ImportSelector接口,接口重写selectImports方法进行事先条件判断PROXY或者ASPECTJ选择不同的配置类。

AsyncConfigurationSelector源码如下:

public class AsyncConfigurationSelector extends AdviceModeImportSelector<EnableAsync> {

    private static final String ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME =
            "org.springframework.scheduling.aspectj.AspectJAsyncConfiguration";     /**
     * Returns {@link ProxyAsyncConfiguration} or {@code AspectJAsyncConfiguration}
     * for {@code PROXY} and {@code ASPECTJ} values of {@link EnableAsync#mode()},
     * respectively.
     */
    @Override
    @Nullable
    public String[] selectImports(AdviceMode adviceMode) {
        switch (adviceMode) {
            case PROXY:
                return new String[] {ProxyAsyncConfiguration.class.getName()};
            case ASPECTJ:
                return new String[] {ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME};
            default:
                return null;
        }
    } }

3. 动态注册Bean

@EnableAspectJAutoProxy使用了这种方式,注解源码如下:

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

EnableAspectJAutoProxy注解中导入了AspectJAutoProxyRegistrar,AspectJAutoProxyRegistrar实现了ImportBeanDefinitionRegistrar接口,在运行时把Bean注册到spring容器中。

AspectJAutoProxyRegistrar的源码如下:

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

    /**
     * Register, escalate, and configure the AspectJ auto proxy creator based on the value
     * of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
     * {@code @Configuration} class.
     */
    @Override
    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);
            }
        }
    } }

推荐阅读

1.Java中Integer.parseInt和Integer.valueOf,你还傻傻分不清吗?
2.SpringCloud系列-整合Hystrix的两种方式)
3.SpringCloud系列-利用Feign实现声明式服务调用)
4.手把手带你利用Ribbon实现客户端的负载均》
5.SpringCloud搭建注册中心与服务注册


限时领取免费Java相关资料,涵盖了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo/Kafka、Hadoop、Hbase、Flink等高并发分布式、大数据、机器学习等技术。
关注下方公众号即可免费领取:

Java碎碎念公众号

SpringBoot中神奇的@Enable*注解?的更多相关文章

  1. springboot中@EnableAsync与@Async注解使用

    springboot中@EnableAsync与@Async注解使用 @Async为异步注解,放到方法上,表示调用该方法的线程与此方法异步执行,需要配合@EnableAsync注解使用. 1.首先演示 ...

  2. Springboot中使用自定义参数注解获取 token 中用户数据

    使用自定义参数注解获取 token 中User数据 使用背景 在springboot项目开发中需要从token中获取用户信息时通常的方式要经历几个步骤 拦截器中截获token TokenUtil工具类 ...

  3. 在Spring-boot中,为@Value注解添加从数据库读取properties支持

    一般我们会把常用的属性放在工程的classpath文件夹中,以property,yaml或json的格式进行文件存储,便于Spring-boot在初始化时获取. @Value则是Spring一个非常有 ...

  4. Spring中的@Enable注解

    本文转载自SpringBoot中神奇的@Enable注解? 导语 在SpringBoot开发过程,我们经常会遇到@Enable开始的好多注解,比如@EnableEurekaServer.@Enable ...

  5. SpringBoot中如何灵活的实现接口数据的加解密功能?

    数据是企业的第四张名片,企业级开发中少不了数据的加密传输,所以本文介绍下SpringBoot中接口数据加密.解密的方式. 本文目录 一.加密方案介绍二.实现原理三.实战四.测试五.踩到的坑 一.加密方 ...

  6. SpringBoot中如何优雅的读取yml配置文件?

    YAML是一种简洁的非标记语言,以数据为中心,使用空白.缩进.分行组织数据,从而使得表示更加简洁易读.本文介绍下YAML的语法和SpringBoot读取该类型配置文件的过程. 本文目录 一.YAML基 ...

  7. SpringBoot 中定时执行注解(@Scheduled、@EnableScheduling)

    项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息.Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor .TaskScheduler 接口. ...

  8. [SpringBoot]SpringBoot中使用redis事务

    本文基于SpringBoot 2.X 事务在关系型数据库的开发中经常用到,其实非关系型数据库,比如redis也有对事务的支持,本文主要探讨在SpringBoot中如何使用redis事务. 事务的相关介 ...

  9. SpringBoot中关于@Enable***的注解详解

    出处:http://blog.csdn.net/qq_26525215 @EnableAspectJAutoProxy @EnableAspectJAutoProxy注解 激活Aspect自动代理 & ...

随机推荐

  1. struts2表单提单细节处理

    1. 上传文件 大部分项目避免不了要上传文件. struts2提供了封闭的上传文件的入口, 网络上也存在大量的插件用于网页表单中上传文件. 由于自己习惯用SSH框架, 所以介绍一下struts2中文件 ...

  2. CentOS7 自定义登录前后欢迎信息

    博客地址:http://www.moonxy.com 一.摘要 本人当前使用的是阿里云 ECS 服务器,操作系统为 linux,发行版为 CentOS 7.4.1708.系统默认都已经提供了欢迎信息, ...

  3. jdk1.8源码阅读

    一.java.lang java的基础类 1.object 所有类的爸爸 registerNatives() Class<?> getClass():返回运行时的类 int hashCod ...

  4. [Linux] Linux下undefined reference to ‘pthread_create’问题解决

    问题的原因:pthread不是Linux下的默认的库,也就是在链接的时候,无法找到phread库中函数的入口地址,于是链接会失败. 解决:在gcc编译的时候,附加要加 -lpthread参数即可解决.

  5. Java职责链模式

    一.定义 职责链模式,就是将能够处理某类请求事件的一些处理类,类似链条的串联起来.请求在链条上处理的时候,并不知道具体是哪个处理类进行处理的.一定程度上实现了请求和处理的解耦. 实际生活中的经典例子就 ...

  6. Flask中的路由、实例化参数和config配置文件

    Flask中的路由 endpoint 别名不能重复,对应的视图函数,默认是视图函数名.endpoint 才是路由的核心.视图函数与路由的对应关系.可以通过url_for 反向创建url # metho ...

  7. 原来python如此神奇

    一.优缺点分析 1.缺点: ① 数学问题的生成中只考虑了消除乘除法加括号的无效情况(例如3*(4+5)或(6*5)/2这样的计算),但没有去掉加减法加括号的无效情况(例如(4+(7+8))或(3-(2 ...

  8. pycharm使用sublime/boxy配色方案

    # 展示效果图 1. github官网连接:https://github.com/simoncos/pycharm-monokai 2.克隆代码并解压文件 3.PyCharm -> File - ...

  9. js校验对象是否全部为空

    function judgeIsNotBlank(obj) { var bool = true; var arr = Object.keys(obj); ; for(var key in obj){ ...

  10. 序列标注(HMM/CRF)

    目录 简介 隐马尔可夫模型(HMM) 条件随机场(CRF) 马尔可夫随机场 条件随机场 条件随机场的特征函数 CRF与HMM的对比 维特比算法(Viterbi) 简介 序列标注(Sequence Ta ...