简体   繁体   English

创建无法自动连线的Spring bean

[英]Create a Spring bean that cannot be autowired

I have a class A that extends B, which implements C. Currently, A takes B has an input argument and is the only defined bean that is an implementation of C, so it gets autowired whenever C is needed. 我有一个扩展了B的类A,该类实现了C。当前,A接受B具有一个输入参数,并且是C的实现中唯一定义的bean,因此在需要C时它将自动装配。

Without changing the ALL of the places where C is needed or the class structure of A/B/C, I need make B a defined bean so the same instance can be re-used. 在不更改需要C的所有位置或A / B / C的类结构的情况下,我需要将B定义为bean,以便可以重复使用同一实例。 The problem is then I have 2 implementations of C (A and B). 问题是我有2个C的实现(A和B)。 Is there a way to mark B so that it cannot be autowired? 有没有办法标记B,使其不能自动接线?

Current: 当前:

  <bean id="A" class="A">
    <constructor-arg>
      <bean class="B">
    </constructor-arg>
  </bean>

Wanted (so same instance of B can be used elsewhere): 想要的(所以B的相同实例可以在其他地方使用):

  <!-- TODO: Somehow mark B so it cannot be autowired -->
  <bean id="B" class="B"/>

  <bean id="A" class="A">
    <constructor-arg ref="B">
  </bean>

  <bean id="Foo" class="Foo">
    <constructor-arg ref="B">
  </bean>

If you want to eliminate a bean from autowiring, then you can set autowire-candidate attribute of that bean tag to false. 如果要消除自动装配的bean,则可以将该bean标记的autowire-candidate属性设置为false。 For example consider your case(Here I am setting B bean's autowire-candidate attribute to false) 例如,考虑您的情况(这里我将B bean的autowire-candidate属性设置为false)。

 <bean id="B" class="B" autowire-candidate="false"/>

  <bean id="A" class="A">
    <constructor-arg ref="B">
  </bean>

  <bean id="Foo" class="Foo">
    <constructor-arg ref="B">
  </bean>

You could use qualifiers attached to @Autowired . 您可以使用附加到@Autowired限定词。

Eg, if you want to wire the bean with id B , you can do the following: 例如,如果要将ID为B的bean连接起来,可以执行以下操作:

@Autowired
@Qualifier("B")
private C c;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM