当前,我正在开发一个使用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());
}
}
}
但是,这不一定是很好的流程。
有什么建议或其他想法吗?
答案 0 :(得分:0)
您可以使用上述注释或@PropertySource等在配置类或主应用程序类的开头指定配置属性文件位置的位置,