【发布时间】:2019-10-21 05:42:31
【问题描述】:
你能解释一下使用@ConfigurationProperties注解的好处吗?
我必须选择我的代码。
首先用@ConfigurationProperties注解:
@Service
@ConfigurationProperties(prefix="myApp")
public class myService() {
private int myProperty;
public vois setMyProperty(int myProperty) {
this.myProperty = myProperty;
}
// And this I can use myProperty which was injected from application.properties (myApp.myProperty = 10)
}
第二个没有@ConfigurationProperties注解。
看起来像这样:
@Service
public class myService() {
private final Environment environment;
public myService(Environment environment) {
this.environment = environment;
}
// And this I can use myProperty which was injected from application.properties (myApp.myProperty = 10)
environment.getProperty("myApp.myProperty")
}
对于一个属性,代码的数量看起来是一样的,但是如果我有大约 10 个属性,第一个选项将有更多的代码样板(为此属性定义 10 个属性和 10 个设置器)。
第二个选项将有一次环境注入,不添加样板代码。
【问题讨论】:
标签: java spring configuration annotations