When to prefer EJB over CDI

While Contexts and Dependency Injection (JSR 299, CDI)  is becoming more and more popular, there is also some confusion about the usage of CDI and EJB. We are sometimes asked by our clients when to prefer one over the other. This is a common misunderstanding, as CDI and EJB are rather used side-by-side, not exclusively. Both are complementary, so there is no need for an either-or choice. Lets look at what both have to offer.

CDI offers all the features necessary for and related to dependency injection. Though part of the Java EE specification, CDI may be used in a Java SE environment as well, making CDI the primary component model in Java.

Besides DI, CDI also offers an easy-to-use event mechanism that allows for effective decoupling of event producers and listeners. Additionally, decorators and interceptors provide a simple approach to aspect orientation and offer ways to add functionality to existing components without touching them.

So, while CDI aims at modularization and separation of concerns, EJB is adding container services. When a bean is defined as EJB (by declaring them as @Stateless or @Stateful), the container takes care of transaction handling, security, concurrency and pooling. EJB also offers asynchronous method invocation and timer services.

To sum it up: EJB = CDI + container services. There is no need to choose between them. Typically you start with POJOs, use the CDI features when needed and make your bean an EJB when any of the afore mentioned features is required.

David Blevins goes into more details in this blogpost: http://blog.dblevins.com/2012/11/cdi-when-to-break-out-ejbs.html

Short URL for this post: http://wp.me/p4nxik-1M9
This entry was posted in Did you know?, Java EE and tagged , , , , , . Bookmark the permalink.

Leave a Reply