在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. u盘重装ubuntu16.04过程遇到的问题

    该博文主要记录ubuntu16.04重装过程中分区问题 1. /swap交换区,Logical(逻辑分区),swap area; 一般为物理内存的2倍; 例如你电脑的运行内存是4G, 则/swap可以 ...

  2. 实现非管理型UPS在linux主机上的停电自动关机

    买了个山特的SANTAK TG-BOX 850 UPS,自带USB通讯线缆.本以为官方软件提供Linux下的CLI命令以监控UPS状态. 官网提供的下载链接巨慢无比不说,CLI下只提供了安装脚本,没有 ...

  3. C#下载http/https的pdf、excel等文件(非在线打开,绕开插件)

    非本服务器文件,如PDF,excel等,下载一般是通过href=‘远程文件的http或者https’的方式下载,但是如果浏览器已经有PDF插件了,则用href不是下载,而是在线打开了,影响体验,所以远 ...

  4. Java的EOF标识?

     这篇是关于JAVA中EOF标识的讲解,之前在工作上碰到过一个问题,有人问过,不能通过判断EOF来知道文件有没有读取完毕吗?其实,还真不能.  直接从JDK接口文档入手,以FileInputStrea ...

  5. 1.html基础知识

    1.html定义: html是一种超文本标记语言,“超文本”是指页面可以包含图片.链接.音乐.程序等非文字元素. Html不是一种编程语言. 2.html5的新特性: 用于绘画的canvas元素: 用 ...

  6. json与java对象的转换,以及struts2对json的支持,实现ajax技术

    这两天学的东西有点多,今天抽个时间写下来,以此作为激励,这两天学了json,ajax,jQuery 一.使用第三方的工具java转换为json类型 首先就是java类型转换为json对象,首先要导入第 ...

  7. 如果有人问你 JFinal 如何集成 EhCache,把这篇文章甩给他

    废话不多说,就说一句:在 JFinal 中集成 EhCache,可以提高系统的并发访问速度. 可能有人会问 JFinal 是什么,EhCache 是什么,简单解释一下. JFinal 是一个基于Jav ...

  8. 第一篇:php开发环境

    Window: 1.XAMPPhttps://www.apachefriends.org/index.html 2.WampServerhttp://www.wampserver.com/ Linux ...

  9. sbt 学习笔记(1)sbt安装和交互式界面使用

    下载sbt: http://www.scala-sbt.org/download.html 解压zip文件F:\sbt-0.13.15 配置环境变量 如果需要可以修改F:\sbt-0.13.15\sb ...

  10. 整理一些大厂的开源平台及github,向他们看齐...

    有人苦恼,该如何突破技术的局限性... 有人羡慕,技术上你怎么懂得这么多... 有人哀叹,唉,我已经学不动了... 我的总结(纯属个人想法):身处IT,就得不断学习和积累,才不会被狠狠地甩在身后.什么 ...