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?
This mode specifies autowiring by property name. Spring container looks at the beans on which auto-wire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
Autowiring Modes byName : The byName mode injects the object dependency according to name of the bean. In such a case, the property and bean name should be the same. It internally calls the setter method. byType : The byType mode injects the object dependency according to type.
The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.
Enabling @Autowired Annotations The Spring framework enables automatic dependency injection. In other words, by declaring all the bean dependencies in a Spring configuration file, Spring container can autowire relationships between collaborating beans. This is called Spring bean autowiring.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With