前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ConfigurationProperties 和 EnableConfigurationProperties 的区别

ConfigurationProperties 和 EnableConfigurationProperties 的区别

作者头像
潇洒
发布2019-06-28 10:43:11
5.1K0
发布2019-06-28 10:43:11
举报
文章被收录于专栏:石头岛石头岛

@EnableConfigurationProperties 测试发现 @ConfigurationProperties@EnableConfigurationProperties 关系特别大。

@EnableConfigurationProperties 文档中解释: 当@EnableConfigurationProperties注解应用到你的@Configuration时, 任何被@ConfigurationProperties注解的beans将自动被Environment属性配置。 这种风格的配置特别适合与SpringApplication的外部YAML配置进行配合使用。

测试发现: 1.使用 @EnableConfigurationProperties 进行注册

代码语言:javascript
复制
@ConfigurationProperties(prefix = "service.properties")
public class HelloServiceProperties {
    private static final String SERVICE_NAME = "test-service";

    private String msg = SERVICE_NAME;
	   set/get
}


@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class)
@ConditionalOnClass(HelloService.class)
@ConditionalOnProperty(prefix = "hello", value = "enable", matchIfMissing = true)
public class HelloServiceAutoConfiguration {

}

@RestController
public class ConfigurationPropertiesController {

    @Autowired
    private HelloServiceProperties helloServiceProperties;

    @RequestMapping("/getObjectProperties")
    public Object getObjectProperties () {
        System.out.println(helloServiceProperties.getMsg());
        return myConfigTest.getProperties();
    }
}

#自动配置设置

代码语言:javascript
复制
service.properties.name=my-test-name
service.properties.ip=192.168.1.1
service.user=kayle
service.port=8080

一切正常,但是 HelloServiceAutoConfiguration 头部不使用 @EnableConfigurationProperties,测访问报错。

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

代码语言:javascript
复制
@ConfigurationProperties(prefix = "service.properties")
@Component
public class HelloServiceProperties {
    private static final String SERVICE_NAME = "test-service";

    private String msg = SERVICE_NAME;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

}

Controller 不变,一切正常,如果注释掉 @Component 测启动报错。 由此证明,两种方式都是将被 @ConfigurationProperties 修饰的类,加载到 Spring Env 中。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-07-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档