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;
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With