Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I inject a Spring dependency by ID?

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?

like image 756
Aaron Digulla Avatar asked Jan 10 '11 15:01

Aaron Digulla


People also ask

How auto inject into Spring a bean by its name?

D. By using the @Autowired annotation and naming the field with the bean name.

Which annotation is used for injecting dependencies in Spring?

@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.

How do you inject a dependency?

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.


1 Answers

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).

like image 165
skaffman Avatar answered Sep 23 '22 09:09

skaffman