johnm johnm - 9 months ago 77
Java Question

Information on @Inject in CDI/Weld and DI/Guice

I'm trying to discern (some of) the difference's between CDI and DI.

What does CDI(JSR-299)'s bring over just DI's (JSR-330) with respect to @Inject?

Is it true that CDI @Injects (just like DI), however the lifecyle of what it has injected, is tied to some context/ scope. If an object exists in a scope when you use @Inject you get the instance that exists in which ever context/scope it was declared to be in. If one does not exist a new one will be created.

So when you want to be sure you are getting the right instance of an object that you inject. ie @Inject MyObject myObj; will get the instance of myObject that is in session scope (assuming I've annotated it as such)

Is this correct?

Answer Source

Disclaimer : I'm working for Red Hat and I'm CDI co-spec lead. So my knowledge on CDI is probably better than on other DI solution. This said, I'll try to give you an objective answer

Yes this is correct

Looking at respective API :

You can see that CDI is far more rich than JSR 330. AtInject specification only defines 1 interface and 5 annotations to assure a common way of declaring and resolving injection. It doesn't provide any rule regarding how the components are managed or nothing about their lifecycle. CDI (which implements JSR 330) is a complete Dependency Injection specification which implementations can be compared to Guice or Spring Core.

Among other things (events, portable extensions, decorators, interceptors) CDI add the notion of context. As you said it allows you to have a component (beans) managed automatically in its own lifecycle. You can inject bean of a longer life in a shorter life one and vice versa (i.e. inject @RequestScoped bean in an @ApplicationScoped bean). The bean manager will do the work to always give you the right bean regarding the active contexts.

CDI has also a newer version with JSR 346 (CDI 1.1) released 9 months ago with Java EE 7. It added a few interesting things regarding the control of bean lifecycle. You can use it in JBoss Wildlfy 8 or Oracle Glassfish 4 applications servers (others servers are still working on their Java EE 7 version) or grab Weld 2.x and bootstrap CDI from a servlet listener or Java SE if you prefer doing the integration yourself.

Right now we're working on version 1.2 and preparing JSR proposal for CDI 2.0.

To learn more about CDI I suggest that you read the Weld documentation (Weld is the CDI Reference Implementation) which is a very good introduction to the specification from a user point of view.