Spring dependency injection to use @Named or @Resource?

There are two separate annotations for injecting dependencies by name in Spring, javax.annotation.Resource and javax.inject.Named . The documentation in Spring indicates that @Resource should be used for injection by name:

If you intend to express an injection caused by annotations by name, do not basically use @Autowired, even if you can technically refer to the bean name via @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 does not matter for the matching process.

The above is a bit confusing as Spring only acts @Resource instead of @Autowired in combination with @Qualifer . @Named is not mentioned until later in the documentation .

JSR-250 defines @Resource , while JSR-330 defines @Inject and @Named . I know that they can be mixed and matched in Spring quite easily. Which JSR to use?

It seems that portability with Guice and CDI will be enjoyable, and therefore use JSR-330 annotations. On the other hand, the documentation also points to a couple of limitations in Spring when using JSR-330 annotations.

What is the best practice (if any) for annotating an injection by name?

Thanks.

+6
source share
1 answer

@Resource is older and supported with Spring 2.5, and @Named support was added in Spring 3.0, and both of them can be used to achieve the same goal as for injections by name.

When using Spring, my concerns regarding the preference of one over the other will be backward compatible with Spring 2.5 and whether javax.inject can be added / assumed to be on the class path or not.

+1
source

All Articles