自动布线同一类的两个不同 bean

2022-09-01 06:29:32

我有一个包装连接池的类,该类从弹簧配置中获取其连接详细信息,如下所示:

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

此 Bean 稍后在服务中使用,并与注释自动连接。@Autowire

我的问题是,我怎么能复制这个豆子,并给它不同的连接细节,然后在服务中。这意味着除了上面,我将有:@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>

并在服务中:

@Autowired //bean of id jedisConnector
JedisConnector beanA;

@Autowired //bean of id jedisConnectorPOD
JedisConnector beanB;

答案 1

你可以与 组合使用,但在这种情况下,我建议使用:@Autowired@Qualifier@Autowired@Resource

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

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

甚至更简单:

@Resource
JedisConnector jedisConnector;

@Resource
JedisConnector jedisConnectorPOD;

答案 2
@Autowired
@Qualifier("jedisConnector")
JedisConnector beanA;

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

推荐