Java 自动装配同一类的两个不同 bean
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4462466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Autowiring two different beans of same class
提问by Noam Nevo
I have a class which wraps a connection pool, the class gets its connection details from a spring configuration as shown below:
我有一个包装连接池的类,该类从 spring 配置中获取其连接详细信息,如下所示:
<bean id="jedisConnector" class="com.legolas.jedis.JedisConnector" init-method="init" destroy-method="destroy">
<property name="host" value="${jedis.host}" />
<property name="port" value="${jedis.port}" />
</bean>
This bean is later used in a service and is autowired with the @Autowire
annotation.
这个 bean 稍后在服务中使用,并与@Autowire
注解自动装配。
My question is, how can i duplicate this bean and give it different connection details and then @Autowire
it in the service.
meaning In addition to above I will have :
我的问题是,如何复制此 bean 并为其提供不同的连接详细信息,然后再将@Autowire
其添加到服务中。意思是除了上述我将有:
<bean id="jedisConnectorPOD" class="com.legolas.jedis.JedisConnector" init-method="init" destroy-method="destroy">
<property name="host" value="${jedis.pod.host}" />
<property name="port" value="${jedis.pod.port}" />
</bean>
and in the service:
并在服务中:
@Autowired //bean of id jedisConnector
JedisConnector beanA;
@Autowired //bean of id jedisConnectorPOD
JedisConnector beanB;
采纳答案by skaffman
You can combine @Autowired
with @Qualifier
, but in this case instead of @Autowired
, I suggest using @Resource
:
您可以@Autowired
与结合使用@Qualifier
,但在这种情况下@Autowired
,我建议使用@Resource
:
@Resource(name="jedisConnector")
JedisConnector beanA;
@Resource(name="jedisConnectorPOD")
JedisConnector beanB;
or even simpler:
甚至更简单:
@Resource
JedisConnector jedisConnector;
@Resource
JedisConnector jedisConnectorPOD;
回答by OrangeDog
@Autowired
@Qualifier("jedisConnector")
JedisConnector beanA;
@Autowired
@Qualifier("jedisConnectorPOD")
JedisConnector beanB;