Search code examples
javaejbjava-ee-6cdi

How do CDI and EJB compare? interact?


I'm having a tough time understanding how the two interact and where the boundary between them lies. Do they overlap? Are there redundancies between them?

I know there are annotations associated with both, but I haven't been able to find a complete list for both with brief descriptions. Not sure if this would help clear up how they differ or where they overlap.

Really just confused. I (think I) understand EJB reasonably well, I guess I'm having a hard time understanding exactly what CDI brings to the table and how it supplants or enhances what EJB already offers.


Solution

  • CDI: it is about dependency injection. It means that you can inject interface implementation anywhere. This object can be anything, it can be not related to EJB. Here is an example of how to inject random generator using CDI. There is nothing about EJB. You are going to use CDI when you want to inject non-EJB services, different implementations or algorithms (so you don't need EJB there at all).
    EJB: you do understand, and probably you are confused by @EJB annotation - it allows you to inject implementation into your service or whatever. The main idea is that class, where you inject, should be managed by EJB container. Seems that CDI does understand what EJB is, so in Java EE 6 compliant server, in your servlet you can write both

    @EJB EJBService ejbService;
    

    and

    @Inject EJBService ejbService;
    

    that's what can make you confusing, but that's probably the only thing which is the bridge between EJB and CDI.

    When we are talking about CDI, you can inject other objects into CDI managed classes (they just should be created by CDI aware frameworks).

    What else CDI offers... For instance, you use Struts 2 as MVC framework (just example), and you are limited here, even using EJB 3.1 - you can't use @EJB annotation in Struts action, it is not managed by container. But when you add Struts2-CDI plugin, you can write there @Inject annotation for the same thing (so no more JNDI lookup needed). This way it enhances EJB power, but as I mentioned before, what you inject with CDI - it does not matter if it is related to EJB or not, and that's its power.

    PS. updated link to the example