Spring 基于 属性 的 bean 自动装配
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{}
你可以有一个配置文件(也可以是一个配置class)
<bean id = "a" class = "A">
<property name="bBean" ref="b"/>
</bean>
<bean id = "b" class = "B">
</bean>
bBean 配置可以在不同的文件中,因此您可以从 classpath 导入它。您不使用 属性 文件,而是使用系统文件 class 路径中的配置文件。如果 B 是不同的实现,那么您可以使用正确的 class.
修改您的配置文件
我想在 属性 文件中指定哪个 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{}
你可以有一个配置文件(也可以是一个配置class)
<bean id = "a" class = "A">
<property name="bBean" ref="b"/>
</bean>
<bean id = "b" class = "B">
</bean>
bBean 配置可以在不同的文件中,因此您可以从 classpath 导入它。您不使用 属性 文件,而是使用系统文件 class 路径中的配置文件。如果 B 是不同的实现,那么您可以使用正确的 class.
修改您的配置文件