【发布时间】:2019-10-20 16:52:55
【问题描述】:
我正在设置一个 Spring Boot 应用程序,其中某些配置是从我的 application.yaml 文件中读取的。我以前做过几次,效果很好,但我想知道是否有更好的方法可以在运行时访问此配置,或者我是否通过不遵循一些最佳实践而产生了可能的问题。
现在提取配置的类被简单地定义为这样的组件:
@Component
@EnableConfigurationProperties
@ConfigurationProperties("myPrefix")
public class MyExternalConfiguration{
private HashMap<String, Boolean> entries= new HashMap<String, Boolean>();
public Boolean getConfigurationForKey(String key) {
return this.entries.get(key);
}
}
然后像这样自动连接到需要访问此配置的其他几个类:
@Component
public class MyClass{
@Autowired
private MyExternalConfiguration myExternalConfiguration;
public void doSomething(){
//...
Boolean someEntry = myExternalConfiguration.getConfigurationForKey(someKey);
}
}
现在,这确实工作得很好。只是我已经看到了这样的配置作为单例处理的示例(尽管不是在 Spring-Boot 环境中)。我想问一下,是否有一些普遍接受的方式来访问外部配置,或者您是否发现我在项目中访问它的方式存在问题。
提前谢谢你!
【问题讨论】:
标签: java spring-boot configuration components singleton