How to autowire by name in Spring with annotations?

Viewed 49470

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?

2 Answers

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;
    }
}
Related