[英]Spring Configuration: 2 beans with same class reference
Spring-configuration: I have created 2 beans with reference to same class but different database sessions. Spring-configuration:我创建了2个bean,引用了同一个类但不同的数据库会话。
<bean id="abc1" class="abc">
<bean id="abc2" class="abc">
Now is there any way to set bean with id "abc1" as default bean for autowiring and use abc2 for autowiring when mentioned explicitly like this: 现在有没有办法将id为“abc1”的bean设置为自动装配的默认bean,并在明确提到时使用abc2进行自动装配:
@Autowiring
@Qualifier("abc2")
private abc obj;
Solution: 解:
<bean id="abc1" class="abc" primary="true">
makes abc1 default one to be autowired. 使abc1默认为自动装配。
for creating an instance of abc2, we can use this: 为了创建abc2的实例,我们可以使用:
@Autowired
@Qualifier("abc2")
private abc obj;
The @primary
annotation or primary
attribute of xml is used exactly for that purpose. xml的@primary
注释或primary
属性完全用于此目的。 Here is the details of the same. 这是相同的细节。 It is pretty well documented here. 这里有很好的记录。
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Primary.html http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Primary.html
So if you mention <bean id="abc1" class="abc" primary="true"/>
it will get priority over abc2
, and you can use @Qualifier
for abc2
wherever you need. 因此,如果你提到<bean id="abc1" class="abc" primary="true"/>
它将优先于abc2
,你可以在任何需要的地方使用@Qualifier
作为abc2
。 Hope this helps. 希望这可以帮助。
If you skip the @Qualifier
annotation, then Spring will lookup for a bean with the same name as the private
member. 如果跳过@Qualifier
注释,则Spring将查找与private
成员同名的bean。 For example: 例如:
@Autowired
private abc abc1; //Spring will search for a bean with id="abc1"
This was you can use abc1
as a default value. 这是你可以使用abc1
作为默认值。
If you don't want to make Spring search for a specific bean, then you can trigger the @Qualifier
and then Spring will not care how the member is called, but will assign it's value to refer to the bean that has the same id
pointed out in the @Qualifier
annotation: 如果你不想让Spring搜索特定的bean,那么你可以触发@Qualifier
,然后Spring不会关心如何调用该成员,但会指定它的值来引用具有相同id
的bean的bean在@Qualifier
注释中:
@Autowired
@Qualifier("abc2")
private abc theNameDoesNotMatter;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.