( 九 ) SpringBoot 之 @EnableConfigurationProperties

( 九 ) Springoot 之 @EnableConfigurationProperties

 

 

1、作用

使用 @EnableConfigurationProperties  注解 是使 使用了 @ConfigurationProperties 注解的类 生效。

 

2、详细说明:

在前面的文章中:( 四 )SpringBoot 配置绑定Java Bean 我们知道 @ConfigurationProperties 的作用是使 javaBean 中的属性 与 全局配置文件 yml 或者 properties 配置文件中配置的值进行绑定, 但是注解了@ConfigurationProperties 的类必须在IOC容器中, 才能进行绑定, 所以我们使用了 @Component 注解来添加组件到容器中,使@ConfigurationProperties 生效。

如果一个配置类只配置了 @ConfigurationProperties 注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的 bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。


3、测试
1、创建 MyTestProperties
@ConfigurationProperties(prefix = "my.test")
public class MyTestProperties {
    private  String  name;
   
    private Integer age;

   ... setter/ getter
}

 

  2、创建自动配置类:MyTestAutoConfiguration

@Configuration
@EnableConfigurationProperties(MyTestProperties.class)
@ConditionalOnClass(MyTestProperties.class)
public class MyTestAutoConfiguration {

}

 

3、创建TestController

@RestController
public class TestPropertiesController {

    @Autowired
    private MyTestProperties  myTestProperties;

    @RequestMapping("/test")
    public Object test() {
        return myTestProperties;
    }
}

 

4、application.properties 配置文件

my.test.name=dwStudy
my.test.age=18

测试: 一切正常, 注释掉 @EnableConfigurationProperties(MyTestProperties.class), 报错。

 

2、不使用 @EnableConfigurationProperties 进行注册,使用 @Component 注册

@ConfigurationProperties(prefix = "my.test")
@Component
public class MyTestProperties {
    private  String  name;
   
    private Integer age;

   ... setter/ getter
}

一切正常

由此证明,两种方式都是将被 @ConfigurationProperties 修饰的类注册到IOC容器中。

 

posted @ 2021-08-06 21:44  邓维-java  阅读(1030)  评论(0)    收藏  举报