目前,我正在开发一个使用Spring配置的项目,并且遇到了一个设计问题。
我在下面发布了一个简化的代码段.
假设我的应用程序有两个客户机,它们是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());
}
}
}然而,这不一定需要是一个良好的流程。
有什么建议或补充意见吗?
发布于 2019-10-07 08:55:58
您可以使用上述注释或@PropertySource等在配置类或主应用程序类的开头指定配置属性的文件位置的位置。
https://stackoverflow.com/questions/58265523
复制相似问题