开发者

Autowiring two different beans of same class

开发者 https://www.devze.com 2023-01-31 11:26 出处:网络
I have a class which wraps a connection pool, the class gets its connection details from a spring configuration as sho开发者_如何学运维wn below:

I have a class which wraps a connection pool, the class gets its connection details from a spring configuration as sho开发者_如何学运维wn below:

<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.

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 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;


You can combine @Autowired with @Qualifier, but in this case instead of @Autowired, I suggest using @Resource:

@Resource(name="jedisConnector")
JedisConnector beanA;

@Resource(name="jedisConnectorPOD")
JedisConnector beanB;

or even simpler:

@Resource
JedisConnector jedisConnector;

@Resource
JedisConnector jedisConnectorPOD;


@Autowired
@Qualifier("jedisConnector")
JedisConnector beanA;

@Autowired
@Qualifier("jedisConnectorPOD")
JedisConnector beanB;
0

精彩评论

暂无评论...
验证码 换一张
取 消