Search code examples
javaspringannotations

Autowiring two different beans of same class


I have a class which wraps a connection pool, the class gets its connection details from a spring configuration as shown 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;

Solution

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