Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 650
Noam Nevo Avatar asked Dec 16 '10 15:12

Noam Nevo


People also ask

Can we create 2 beans of same class?

The limitation of this approach is that we need to manually instantiate beans using the new keyword in a typical Java-based configuration style. Therefore, if the number of beans of the same class increases, we need to register them first and create beans in the configuration class.

Can you Autowire byType when more than one bean with the same type exists?

Autowiring using property type. Allows a property to be autowired if exactly one bean of property type exists in the container. If more than one exists, it's a fatal exception is thrown, which indicates that you may not used byType autowiring for that bean.

How do you Autowire a particular bean if more than one bean of the same class type?

The default autowiring is by type, not by name, so when there is more than one bean of the same type, you have to use the @Qualifier annotation.


2 Answers

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;
like image 160
skaffman Avatar answered Oct 23 '22 03:10

skaffman


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

@Autowired
@Qualifier("jedisConnectorPOD")
JedisConnector beanB;
like image 44
OrangeDog Avatar answered Oct 23 '22 03:10

OrangeDog