基于属性的Spring bean自动装配

时间:2017-03-14 19:24:37

标签: java spring javabeans

我想在属性文件中指定哪个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 是它的实现。
有没有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

您可以使用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配置可以位于不同的文件中,因此您可以从类路径中导入它。您可以在classpath或systemfile中使用配置文件,而不是使用属性文件。如果B是不同的实现,那么您使用正确的类修改配置文件。

相关问题