Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Spring understand @Inject replacing Weld as a JSR-299 implementation?

I have noticed from several web pages that apparently Spring 3.0 supports @Inject from JSR-330. As we would really like to use JSR-299 syntax for dependency injection in our libraries for both web apps and stand-alone applications, and have alternatives to Weld, it would be nice if Spring could do this.

Being a novice to Spring, I tried downloading the Spring Framework distribution and put all jars on the Eclipse build path. No Inject annotation so my existing test project using Weld did not compile.

Can this be done with Spring? What do I need to do to get it running?

(I am aware that Guice eventually will support this too. It is only in SVN for now, and if there is an official Spring release which can, that would be better.)


It can be done. The JSR-330 jar must be downloaded seperately, and cglib to parse the manually written @Configuration classes, plus a commons logging implementation.

The largest difference from Weld seems to be that the wiring needs to be manually written instead of magically found (a bit more cumbersome, but may make more robust applications), plus the startup time is much less. I am still new to Spring - is there a way to have @Configuration classes autodiscovered?

like image 997
Thorbjørn Ravn Andersen Avatar asked Jun 16 '10 17:06

Thorbjørn Ravn Andersen


2 Answers

From the Spring 3.0.x Reference documentation:

JSR 330's @Inject annotation can be used in place of Spring's @Autowired in the examples below. @Inject does not have a required property unlike Spring's @Autowire annotation which has a required property to indicate if the value being injected is optional. This behavior is enabled automatically if you have the JSR 330 JAR on the classpath.

So you can make your code agnostic of the DI framework by using @Inject, but you still need to include a jar with the javax.inject classes in your project because Spring does not ship them itself. You can find the relevant jar in the downloads section at JSR-330's Google Code site.

like image 155
Ophidian Avatar answered Nov 08 '22 11:11

Ophidian


The javax.inject package is not included as part of Spring 3, but it does support it if it's present.

If you look at the source for AutowiredAnnotationBeanPostProcessor, you'll see the constructor uses reflection to locate javax.inject.Inject, and logs a message if it finds it. There's no compile-time dependency on it.

You'll need to locate the JSR-330 JARs from some other source (e.g. the JavaEE 6 SDK).

like image 44
skaffman Avatar answered Nov 08 '22 09:11

skaffman