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.
@Resource is older and is supported since Spring 2.5 while @Named support has been added in Spring 3.0 and both of them can be used to achieve the same purpose of injection-by-name.
When using Spring, my concerns for preferring one over the other would be backward compatibility with Spring 2.5 and whether javax.inject can be added/assumed-to-be on the classpath or not.
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