java - Spring - ConfigurationProperties 用法
问题描述
目前,我正在开发一个使用 Spring 配置的项目,但遇到了设计问题。
我在下面发布了一个简化的代码段。
假设我的应用程序有 2 个客户端,它们是 Spring@Component
并用于@Value
注入配置值。
@Component
public class FirstClient implements Client {
private String hello;
public FirstClient(@Value("hello.first") String hello) {
this.hello = hello;
}
// do some stuff with hello
}
@Component
public class SecondClient implements Client {
private String hello;
public SecondClient(@Value("hello.second") String hello) {
this.hello = hello;
}
// do some stuff with hello
}
通过使用这种方法,我可以轻松地@Autowire
新建 Spring 组件。但是,来自“非 Spring 背景”,我发现神奇地将前面提到的注释用于任何代码操作都有些问题。
我的第二种方法是引入配置类:
@ConfigurationProperties(prefix = "hello")
public class DummyProperties {
private String first;
private String second;
// get/set omitted
}
public class FirstClient implements Client {
private String hello;
public FirstClient(String hello) {
this.hello = hello;
}
// do some stuff with hello
}
public class SecondClient implements Client {
private String hello;
public SecondClient(String hello) {
this.hello = hello;
}
// do some stuff with hello
}
加入逻辑将是:
@Component
@EnableConfigurationProperties(DummyProperties.class)
public class ClientCreator {
private DummyProperties props;
public ClientCreator(DummyProperties props) {
this.props = props;
}
public Client create(boolean isSatisfied) {
// some custom check logic
if (isSatisfied) {
return new FirstClient(props.getFirst());
} else {
return new SecondClient(props.getSecond());
}
}
}
然而,这并不一定需要是一个好的流程。
有什么建议或其他想法吗?
解决方案
您可以使用上述注释或@PropertySource 等在配置类或主应用程序类的开头指定配置属性文件位置的位置,
推荐阅读
- apache-flink - 输出中存在重复键
- amazon - 如何在不注册 Associate Program 的情况下获取 Amazon 产品信息?
- mysql - 出现语法错误,但非常不确定出了什么问题
- c - 如何在没有 strstr 函数的情况下更改此代码?
- mysql - MySQL解析\u0080以上的字符
- asp.net-core - ASP.NET Core 2.0 - 用户在一小时内注销
- java - 通过 JDBC URL 使用 TestContainers DB 但使用 @Rule 时出错
- python - Tweepy 搜索查询问题
- python-3.x - Python 请求基于 URL 的程序从气候网站 (http://www.climate.weather.gc.ca) 自动批量下载数据
- ruby - 什么是正则表达式来获取一个或多个单词字符的字符串,除了只有数字字符的字符串?