首页 > 编程语言 > 详细

Spring @Enable模块装配

时间:2020-06-01 10:46:07      阅读:31      评论:0      收藏:0      [点我收藏+]

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

Spring @Enable模块装配

原文:https://www.cnblogs.com/fjf3997/p/13023820.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!