我们实际上使用 Spring Boot 的 @ConfigurationProperties
作为基本上的配置映射器:它为我们提供了在对象上映射属性的简单快捷方式。
@ConfigurationProperties("my.service")
public class MyService {
private String filePrefix;
private Boolean coefficient;
private Date beginDate;
// getters/setters mandatory at the time of writing
public void doBusinessStuff() {
// ...
}
}
尽管在我们制作应用程序原型(prototype)时,这极大地提高了工作效率,但我们开始质疑这是否是正确的用法。
我的意思是,配置属性在 Spring Boot 的上下文中具有不同的状态,它们通过执行器端点公开,它们可用于触发条件 bean,并且似乎更面向技术配置属性。
问题:在任何业务属性/值上使用此机制是否“正确”,还是纯粹的滥用?
我们错过了任何潜在的缺点吗?
现在我们唯一担心的是我们不能在不可变类上使用@ConfigurationProperties
,这与Spring Boot跟踪器上的这个问题密切相关:Allow field based @ConfigurationProperties binding
最佳答案
如果您的属性代表可根据环境/配置文件进行配置的内容,则该机制就是为此而设计的。虽然我有点不清楚你的意思 “在对象上映射属性”。
一般来说,我不喜欢这种风格,特别是当您的 bean 有多个属性需要设置时。更标准的习惯用法是使用一个类来封装用于创建 bean 的属性/设置:
@ConfigurationProperties("my.service")
public class MyServiceProperties {
private String filePrefix;
private Boolean coefficient;
private Date beginDate;
// getters/setters mandatory at the time of writing
}
那么你的服务类将如下所示:
@EnableConfigurationProperties(MyServiceProperties.class)
public class MyService {
@Autowired
private MyServiceProperties properties;
//do stuff with properties
public void doBusinessStuff() {
// ...
}
}
这至少允许您通过其构造函数轻松地将属性传递到不可变类中(复制任何可变属性)。如果您发现应用程序的其他部分需要一些共享配置,还可以重用属性 bean。
关于java - Spring Boot @ConfigurationProperties 正确用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30073582/