自动装配同一类的两个不同的bean

时间:2022-03-04 19:17:36

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;

2 个解决方案

#1


34  

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;

#2


36  

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

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

#1


34  

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;

#2


36  

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

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