36

I have several beans of the same class defined:

  @Bean
  public FieldDescriptor fullSpotField() {
     FieldDescriptor ans = new FieldDescriptor("full_spot", String.class);
     return ans;
  }

  @Bean
  public FieldDescriptor annotationIdField() {
     FieldDescriptor ans = new FieldDescriptor("annotationID", Integer.class);
     return ans;
  }

consequently when I autowire them

   @Autowired
   public FieldDescriptor fullSpotField;

   @Autowired
   public FieldDescriptor annotationIdField;

I get an exception

NoUniqueBeanDefinitionException: No qualifying bean of type [...FieldDescriptor] is defined: expected single matching bean but found ...

How to autowire by name as it possible in XML config?

Dims
  • 47,675
  • 117
  • 331
  • 600

2 Answers2

58

You can use @Qualifier to solve it.

In your case you can make:

 @Bean(name="fullSpot")
 // Not mandatory. If not specified, it takes the method name i.e., "fullSpotField" as qualifier name.
  public FieldDescriptor fullSpotField() {
     FieldDescriptor ans = new FieldDescriptor("full_spot", String.class);
     return ans;
  }

  @Bean("annotationIdSpot")
  // Same as above comment.
  public FieldDescriptor annotationIdField() {
     FieldDescriptor ans = new FieldDescriptor("annotationID", Integer.class);
     return ans;
  }

and subsequently you can inject using:

   @Autowired
   @Qualifier("fullSpot")
   public FieldDescriptor fullSpotField;

   @Autowired
   @Qualifier("annotationIdSpot")
   public FieldDescriptor annotationIdField;
  • 2
    I found that `@Qualifier` is not required near bean creation methods, it is sufficient to add this annotation along with `@Autowired` – Dims Mar 23 '16 at 19:10
  • 1
    @Dims You are right. If `Qualifier ` is not specified at bean creation method, it takes the method name ex, "fullSpotField" as qualifier name for the first bean. – Madhusudana Reddy Sunnapu Mar 24 '16 at 02:28
  • 1
    Useful tip, you can label one of the beans as `@Primary`, if you don't want to have to put a `@Qualifier` on every single one of your beans.It will default to the `@Primary` if there's no `@Qualifier`. – joshaidan Apr 10 '18 at 19:25
0

Its a very simple case of "Autowiring By Name" beans gets registered into the container by itself, but might require the constructor injection when using autowiring by name.

You can go ahead and try like this, Where ever you are autowiring the 2 beans which are specified above,

class ExampleClass {
    @Autowired
    public FieldDescriptor fullSpotField;

    @Autowired
    public FieldDescriptor annotationIdField;

    public ExampleClass(FieldDescriptor fullSpotField,FieldDescriptor annotationIdField ){
        super();
        this.fullSpotField = fullSpotField;
        this.annotationIdField = annotationIdField;
    }
}