简体   繁体   English

基于属性自动装配bean

[英]Autowiring a bean based on a property

I have two beans, beanA and beanB , in my Spring config. 我的Spring配置中有两个bean, beanAbeanB Both of these beans implement the same interface. 这两个bean都实现了相同的接口。 I have a class with an autowired field of the interface type (ie it will be populated with an instance of beanA or beanB ). 我有一个具有接口类型的自动装配字段的类(即它将填充beanAbeanB的实例)。

Initially there was only one bean, so I simply used the @Autowired annotation and the field was populated. 最初只有一个bean,所以我只使用了@Autowired注释,并填充了该字段。 However, now there's two potential beans that could be autowired. 但是,现在有两个可以自动装配的潜在bean。 I want to autowire the bean based on the existence of a property in one of my .properties resources. 我想根据我的一个.properties资源中是否存在属性来自动装配bean。 Is there any elegant way to do this? 有没有优雅的方法来做到这一点?

The solution I'm using now is to use the @Qualifier annotation on the autowired field to specify beanA and then make a check to see if the property exists in code. 我现在使用的解决方案是在autowired字段上使用@Qualifier注释来指定beanA ,然后检查该属性是否存在于代码中。 If it does, I reassign the field to an instance of beanB . 如果是,我将该字段重新分配给beanB的实例。 It's a very clunky way of doing it, so I'm looking for a better option. 这是一种非常笨重的方式,所以我正在寻找更好的选择。

Apart from the newer feature of bean profiles, you can also take advantage of FactoryBean which instantiate a bean at the time of access. 除了bean配置文件的新功能之外,您还可以利用 FactoryBean ,它在访问时实例化bean。 The idea is to inject the FactoryBean with the bean types (eg fqcn.BeanA or fqcn.BeanB ). 我们的想法是向FactoryBean注入bean类型(例如fqcn.BeanAfqcn.BeanB )。 Then factory bean will return the bean factory to instantiate the correct type of the bean that you may need. 然后工厂bean将返回bean工厂以实例化您可能需要的正确类型的bean。 The configuration of FactoryBean then can take advantage of properties coming from a resource bundle. 然后, FactoryBean的配置可以利用来自资源包的属性。

Bean profiles could be great fit for this - based on the "active" profile let one or the other bean be created. Bean配置文件非常适合这种情况 - 基于“活动”配置文件,可以创建一个或另一个bean。

Somewhat of an older article, but is still a good reference to profiles in Spring 3.1- http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/ 有些旧文章,但仍然是Spring 3.1中配置文件的一个很好的参考资料 - http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/

Spring Profile can help Spring Profile可以提供帮助

Configuration Changes 配置更改

web.xml web.xml中

<context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>a</param-value>
    </context-param>

spring-beans.xml with profiles. 带有配置文件的spring-beans.xml。 Profile value can behave as the property value for decision making. 配置文件值可以作为决策的属性值。

<bean id="A" profile="a"/>
<bean id="B" profile="b"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM