There are two separate annotations to perform dependency injection by name in Spring, javax.annotation.Resource
and javax.inject.Named
. The documentation at Spring indicates @Resource
should be used for injection by name:
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.
The above is a bit confusing, as Spring is only advocating @Resource
instead of @Autowired
combined with @Qualifer
. There is no mention of @Named
until later in the documentation.
JSR-250 defines @Resource
, whereas JSR-330 defines @Inject
and @Named
. I know they can be mixed-and-matched within Spring fairly easily. Which JSR to use?
It seems like portability with Guice and CDI would be nice, and hence to use the JSR-330 annotations. On the other hand, the documentation also points out at a couple of limitations within Spring when using JSR-330 annotations.
What is the best practice (if there is one) for annotation injection-by-name?
Thank you.