• Spring @Enable模块装配


    Spring @Enable模块装配

    定义

    Spring Framework 3.1 开始支持”@Enable 模块驱动“。所谓“模块”是指具备相同领域的功能组件集合, 组合所形成一个独立
    的单元。比如 Web MVC 模块、AspectJ代理模块、Caching(缓存)模块、JMX(Java 管 理扩展)模块、Async(异步处
    理)模块等。

    注解模块举例

    SpringBoot实例 解释
    @EnableAutoConfiguration 自动装配模块
    @EnableManagementContext Actuator 管理模块
    @EnableConfigurationProperties 配置属性绑定模块
    @EnableOAuth2Sso OAuth2 单点登录模块

    实现方式

    注解驱动方式(实现注解@EnableHelloWorld)

    1. 编写配置类,添加@Configuration注解
    @Configuration
    public class HelloWorldConfiguration {
        @Bean
        public String helloWorld() { // 方法名即 Bean 名称
            return "Hello,World 2020";
        }
    }
    
    1. 编写@Enablexxx注解,添加@Import(HelloWorldConfiguration.class)导入
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @Documented
    @Import(HelloWorldConfiguration.class)
    public @interface EnableHelloWorld {
    }
    
    1. 测试
    @EnableHelloWorld
    public class EnableHelloWorldBootstrap {
        public static void main(String[] args) {
            ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableHelloWorldBootstrap.class)
                    .web(WebApplicationType.NONE)
                    .run(args);
    
            // helloWorld Bean 是否存在
            String helloWorld =
                    context.getBean("helloWorld", String.class);
            System.out.println("helloWorld Bean : " + helloWorld);
            // 关闭上下文
            context.close();
        }
    }
    

    接口编程方式(实现注解@EnableHelloWorld)

    1. 编写config配置类
    @Configuration
    public class HelloWorldConfiguration {
        @Bean
        public String helloWorld() { // 方法名即 Bean 名称
            return "Hello,World 2020";
        }
    }
    
    1. 编写类实现ImportSelector接口,此方法可以增加一些条件判断语句进行删选
    public class HelloWorldImportSelector implements ImportSelector {
        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            return new String[]{HelloWorldConfiguration.class.getName()};
        }
    }
    
    1. 编写@Enablexxx注解,使用@Import(HelloWorldImportSelector.class)注解导入
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @Documented
    @Import(HelloWorldImportSelector.class)
    public @interface EnableHelloWorld {
    }
    
    1. 测试
      同上
    2. debug下查看调用顺序

    HelloWorldImportSelector -> HelloWorldConfiguration -> HelloWorld

  • 相关阅读:
    mysql8.0授权远程登录
    vbox 网络配置
    dnmp安装
    Unix/Linux环境C编程入门教程(7) OPENBSDCCPP开发环境搭建
    Unix/Linux环境C编程入门教程(6) 安装Fedora C/C++开发环境
    Unix/Linux环境C编程入门教程(5) Red Hat Enterprise Linux(RHEL)环境搭建
    Unix/Linux环境C编程入门教程(4) Debian Linux环境搭建
    C语言入门(8)——形参与实参
    C语言入门(7)——自定义函数
    C语言入门(6)——C语言常用数学函数
  • 原文地址:https://www.cnblogs.com/fjf3997/p/13023820.html
Copyright © 2020-2023  润新知