Spring @Enable模块驱动

image.png
从Spring Framework 3.x开始,支持“@Enable模块驱动”

  • 模块:具备相同另据的功能组件集合,组合形成的一个独立的单元,如MVC、AspwctJ代理、Async异步处理模块等

@Enable模块驱动

Spring Framework 3.1种,框架实现者有意识地形成了一种新的设计模式,引入
“@Enable模块驱动”用于简化装配、实现按需装配、屏蔽组件集合装配的细节,在后续的Spring Framework、Spring Boot和Spring Cloud中都使用


该模式必须手动触发,实现的Annotation必须标注在某个配置Bean种,同时实现该模式的成本相对较高,尤其是在理解其中原理和加载机制及单元测试方面

  • Spring Framework的@Enable注解及激活模块
    1.@EnableWebMvc:WebMVC模块
    2.@EnableTransactionManagement:事务管理模块
    3.@EnableCaching:Caching模块
    4.@EnableMBeanExport:JMX模块(Java扩展管理)
    5.@EnableAsync:异步处理模块
    6.@EnableWebFlux:Web Flux模块
    7.@EnableAspectJAutoProxy:AspectJ代理模块
  • Spring Boot的@Enable注解及激活模块
    1.@EnableAutoConfiguration:自动装配模块
    2.@EnableManagementContext:Actuator管理模块
    3.@EnableConfigurationProperties:配置属性绑定模块
    4.@EnableOAuth2Sso:OAuth2单点登录模块
  • Spring Cloud的@Enable注解及激活模块
    1.@EnableEurekaServer:Eureka服务器模块
    2.@EnableConfigServer:配置服务器模块
    3.@EnableFeignClients:Feign客户端模块
    4.@EnableZuulProxy:服务网关Zuul模块
    5.@WnableCircuitBreaker:服务熔断模块

自定义@Enable模块驱动

@Enable模块驱动实现方式大致分为2类

  • 注解驱动:较容易(@Configuration类和@Bean方法声明类)
  • 接口编程:较难(ImpoetSelector或ImportBeanDefinitionRegistrar的实现类)
    无论如何实现均需要@Impor作为元注解,@ImportResource用于导入XML配置文件,@Import用于导入一个或多个ConfigurationClass,将其注册为Spring Bean,也可以用于声明至少一个@Bean方法的类,以及ImpoetSelector或ImportBeanDefinitionRegistrar的实现类

基于注解驱动实现@Enable模块

以@EnableWebMvc为例的实现样板
image.png
image.png

  • 自定义注解驱动
@EnableHelloWorld
@Configuration
public class EnableHelloWorldBootstrap {

    public static void main(String[] args) {
        // 构建 Annotation 配置驱动 Spring 上下文
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 注册 当前引导类(被 @Configuration 标注) 到 Spring 上下文
        context.register(EnableHelloWorldBootstrap.class);
        // 启动上下文
        context.refresh();
        // 获取名称为 "helloWorld" Bean 对象
        String helloWorld = context.getBean("helloWorld", String.class);
        // 输出用户名称:"Hello,World"
        System.out.printf("helloWorld = %s \n", helloWorld);
        // 关闭上下文
        context.close();
    }
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(HelloWorldConfiguration.class) // 导入 HelloWorldConfiguration
public @interface EnableHelloWorld {
}
@Configuration
public class HelloWorldConfiguration {

    @Bean
    public String helloWorld() { // 创建名为"helloWorld" String 类型的Bean
        return "Hello,World";
    }
}

image.png
可见Spring自动装配加载了helloWorld Bean

基于“接口编程”实现@Enable模块

//TODO

@Enable模块驱动原理

//TODO

Spring Web 自动装配

“自动装配”是Spring Boot的三大特征,可分为Web应用和非Web应用




这个家伙很懒,啥也没有留下😋