21

@Autowired by constructor looks for beans by type. How to inject a bean by name to a constructor using autowired annotation? I have 2 beans of same type but I need to inject it to constructor of another same class based on the bean name. How do I do it?

XML:

 <bean id="A" class="com.Check"/>
 <bean id="B" class="com.Check"/>

Java:

Class C {

   private Check check;

   @Autowired
   public C(Check check){
       this.check = check
   }

  }

When I do this I get an exception telling me that I have 2 beans of same type check but it requires there to be just one bean of that type. How can I inject the bean with id="B" into this class C through constructor injection?

In my applicationContext.xml I have mentioned autowire="byType". I need to autowire byName only in this particular class rest all it needs to be autowired by Type only

4

1 回答 1

31

您应该将 @Qualifier 注释与您的目标 bean id 一起用于构造函数参数。

<bean id="A" class="com.Check"/>
<bean id="B" class="com.Check"/>

Class C {

   private Check check;

   @Autowired
   public C(@Qualifier("A") Check check){ //<-- here you should provide your target bean id
      this.check = check
   }
}
于 2013-11-10T08:45:16.847 回答