What is javax.inject.Named annotation supposed to be used for?
I am trying to understand the javax.inject
package and I am not clear what the javax.inject.Named
annotation is supposed to be used for. The Javadoc does not explain the the idea behind it.
Javadoc is at http://download.oracle.com/javaee/6/ap开发者_运维知识库i/javax/inject/Named.html
I am using Spring 3.0 to write some sample programs, by putting @Named
on a bean it seems to add it to the bean factory but the Javadoc description is so light I can't tell if that is the standard behavior or Spring specific behavior.
My questions are:
- What is the difference between
@Named
and@Qualifier
- How are you supposed to tell the Runtime system a class should be injectable in other classes what's the annotation for that? The equivalent of
@Component
in Spring?
Update 1 there is an excellent explanation of @Named
and @Qualifier
at Nice article about @Named
and @Qualifier
https://dzone.com/articles/java-ee6-cdi-named-components thanks @xmedeko for linking to it the comment below.
Use @Named
to differentiate between different objects of the same type bound in the same scope.
@Named("maxWaitTime")
public long maxWaitTimeMs;
@Named("minWaitTime")
public long minWaitTimeMs;
Without the @Named
qualifier, the injector would not know which long to bind to which variable.
If you want to create annotations that act like
@Named
, use the@Qualifier
annotation when creating them.If you look at
@Named
, it is itself annotated with@Qualifier
.
@Inject
instead of Spring’s @Autowired
to inject a bean.
@Named
instead of Spring’s @Component
to declare a bean.
Those JSR-330 standard annotations are scanned and retrieved the same way as Spring annotation (as long as the following jar
is in your classpath)
Regarding #2, according to the JSR-330 spec:
This package provides dependency injection annotations that enable portable classes, but it leaves external dependency configuration up to the injector implementation.
So it's up to the provider to determine which objects are available for injection. In the case of Spring it is all Spring beans. And any class annotated with JSR-330 annotations are automatically added as Spring beans when using an AnnotationConfigApplicationContext.
The primary role of the @Named annotation is to define a bean for the purpose of resolving EL statements within the application, usually through JSF EL resolvers. Injection can be performed using names but this was not how injection in CDI was meant to work since CDI gives us a much richer way to express injection points and the beans to be injected into them.
精彩评论