In the last couple of days I spent some time experimenting a little bit with CDI, the standard of the Java EE 6 platform for dependency injection services.
I must say that I really like that spec, as it hits the sweet spot between specifying features that provide a value out of the box (type-safe DI, eventing, interceptor services etc.) and being open enough to allow people to build totally new stuff based on it (using portable extensions).
I've got the feeling we're going to see a lot of exciting things based on CDI within the near future. Actually this reminds me a bit of Java annotations. Having been introduced with Java 5, just over time people started using them for more and more use cases that had not been foreseen in the first place.
Anyway, to do something practical with CDI I built a small portable extension which allows to retrieve JSR 223 scripting engines using dependency injection.
Just annotate any injection points of type javax.script.ScriptEngine
with one of the qualifier annotations @Language
, @Extension
or @MimeType
. The following code extract shows an example of a JavaScript engine (for example the Rhino engine shipping with Java 6) being injected into some managed bean, where it can be used for arbitrary script evaluations:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@RequestScoped public class MyBean { @Inject @Language("javascript") private ScriptEngine jsEngine; // ... public void foo() throws ScriptException { assert 42.0d == (Double)jsEngine.eval("2 * 21"); // ... } } |
The extension can be found in my Maven repository. Just add the following dependency to your POM in order to use it:
1 2 3 4 5 |
<dependency> <groupId>de.gmorling.cdi.extensions</groupId> <artifactId>scripting-extension</artifactId> <version>0.1</version> </dependency> |
In case you want to take a look at the source code (which is just a few lines), you can check it out from GitHub. As always, any ideas for improvement or other feedback are highly appreciated.