[英]Spring bean autowiring based on property
我想在屬性文件中指定哪個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是其實現。
有什么更好的方法嗎?
您可以使用Spring的常規配置來執行此操作。
class A{
B bBean;
...//setters/getters here.
}
class B{}
您可以有一個配置文件(也可以是配置類)
<bean id = "a" class = "A">
<property name="bBean" ref="b"/>
</bean>
<bean id = "b" class = "B">
</bean>
bBean配置可以位於其他文件中,因此您可以從類路徑中導入它。 您可以使用類文件或系統文件中的配置文件來代替使用屬性文件。 如果B是不同的實現,則可以使用正確的類來修改配置文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.