I have several beans with the same type (BeanType
). How do I inject them by ID with an annotation? Say:
@Autowired @ID("bean1") public void setBean( BeanType bean ) { }
But there is no annotation @ID
.
I only found @Qualifier
which would mean that I would have to give all my beans IDs and qualifiers. Surely, there is a more simple way?
D. By using the @Autowired annotation and naming the field with the bean name.
@Autowired annotation is used to let Spring know that autowiring is required. This can be applied to field, constructor and methods. This annotation allows us to implement constructor-based, field-based or method-based dependency injection in our components.
The injector class injects dependencies broadly in three ways: through a constructor, through a property, or through a method. Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.
Simplest solution is to use @Resource
@Resource(name="bean1") public void setBean( BeanType bean ) { }
Incidentally, @Qualifier
is used to refer to beans by ID for use with @Autowired
, e.g
@Autowired @Qualifier("bean1") public void setBean( BeanType bean ) { }
where bean1
is the ID of the bean to be injected.
See the Spring manual:
For a fallback match, the bean name is considered a default qualifier value. Thus you can define the bean with an id "main" instead of the nested qualifier element, leading to the same matching result. However, although you can use this convention to refer to specific beans by name,
@Autowired
is fundamentally about type-driven injection with optional semantic qualifiers. This means that qualifier values, even with the bean name fallback, always have narrowing semantics within the set of type matches; they do not semantically express a reference to a unique bean id.
and
If you intend to express annotation-driven injection by name, do not primarily use
@Autowired
, even if is technically capable of referring to a bean name through@Qualifier
values. Instead, use the JSR-250@Resource
annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.
I prefer @Resource
, it's cleaner (and not Spring-specific).
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