Toumi
Toumi

Reputation: 3155

What is the difference between CDI (Contexts and Dependency Injection) and DI (Dependency Injection)

The official documentation says

The most fundamental services provided by CDI are as follows:

but i still do not get the difference. Spring for example is DI and we still can access the context in it.

Upvotes: 4

Views: 3345

Answers (2)

Gilberto
Gilberto

Reputation: 985

Reading How To Use DI in Java EE 6 by Antonio Goncalves, give us excellent understanding. I will quote one important part of it:

These two specifications are complementary and can’t be used one without the other.

Dependency Injection for Java (aka @Inject) defines a set of annotations (@Inject, @Named, @Provider, @Qualifier, @Scope and @Singleton) mainly used for injection. If you download this JSR (which is actually just Javadoc) and read through it, you will be surprised to see that no semantic is defined (i.e. the injection behaviour is not portable across implementation). This specification is implemented in Spring 3, Guice, and also in Java EE 6 with CDI. You will find the DI annotations in the javax.inject package.

And finally

Contexts and Dependency Injection gives semantic to JSR 330 and adds more features such as context management, events, decorators and enhanced interceptors (AOP).

Upvotes: 3

no_fate
no_fate

Reputation: 1705

CDI gives you more opportunities. And provide it in some different way that Spring - is trying to rest more on the possibility of verification at compile time. But sometimes it is look like overhead. In a very small project EJB plus DI from JSF for example will be quite enough. But you can use CDI, only first it is worth reading more carefully about the main advantages in comparison with EJB's DI. There are many little details and you must think about where to use it.

I take it from "https://javatalks.ru/topics/40299" and translate the closest answer for you. And I can advise to read this: "https://blogs.oracle.com/enterprisetechtips/using-cdi-and-dependency-injection-for-java-in-a-jsf-20-application" this is good article from Oracle engineer about using CDI and DI

Upvotes: 2

Related Questions