7
votes

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.

1
The limitations mentioned just refer to how Spring will use those annotations, and how the annotations that Spring introduces are much more robust for working with Spring specifically.nicholas.hauschild
The limitations do not seem all that onerous. Though they do exist. It seems a lot of this would be simpler if Spring had also adopted the additional CDI annotations.Saish

1 Answers

1
votes

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