[英]Spring bean autowiring based on property
I want to specify in property file, which bean will be autowired. 我想在属性文件中指定哪个bean将被自动装配。
I found the solutions but all of them are using @Profile annotation, which means that they are based on specified profile, not specified property. 我找到了解决方案,但是所有解决方案都使用@Profile批注,这意味着它们基于指定的配置文件而不是指定的属性。
I did it in that way: 我以这种方式做到了:
@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 type I want to autowire is interface WebService , GraphQLService and RestService are it's implementations. 我要自动装配的Bean类型是接口WebService , GraphQLService和RestService是其实现。
Is there any better way to do this? 有什么更好的方法吗?
You can do this using the normal configuration of Spring. 您可以使用Spring的常规配置来执行此操作。
class A{
B bBean;
...//setters/getters here.
}
class B{}
You can have a configuration file (It also can be a configuration class) 您可以有一个配置文件(也可以是配置类)
<bean id = "a" class = "A">
<property name="bBean" ref="b"/>
</bean>
<bean id = "b" class = "B">
</bean>
The bBean configuration can be in a different file, so you can import it from you classpath. bBean配置可以位于其他文件中,因此您可以从类路径中导入它。 Instead of using a property file you use a configuration file in the classpath o systemfile.
您可以使用类文件或系统文件中的配置文件来代替使用属性文件。 If B is a different implementation then you modify your config file with the right class.
如果B是不同的实现,则可以使用正确的类来修改配置文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.