【发布时间】:2017-03-15 04:20:59
【问题描述】:
我想在属性文件中指定,哪个 bean 将被自动装配。
我找到了解决方案,但它们都使用 @Profile 注释,这意味着它们基于指定的配置文件,而不是指定的属性。
我就是这样做的:
@Configuration
public class WebServiceFactory {
@Value("${webservice}")
private String webService;
@Lazy
@Autowired
private GraphQLService graphQLService;
@Lazy
@Autowired
private RestService restService;
@Primary
@Bean
WebService getWebService() {
switch (webService) {
case "graphQlService":
return graphQLService;
case "restService":
return restService;
default:
throw new UnsupportedOperationException("Not supported web service.");
}
}
}
我要自动装配的 Bean 类型是接口 WebService,GraphQLService 和 RestService 是它的实现。
有没有更好的方法来做到这一点?
【问题讨论】:
-
你想根据属性文件将一个bean注入另一个吗?或者你有很多 Webservices 实现和很多 GraphQSService 实现,你想在运行时注入一个特定的实现?
-
是的,我有 application.properties 文件,并且有值“webservice”。 Spring 应该读取这个值并注入正确的 bean。