Tuesday, February 19, 2013

JSF @ManagedBean vs CDI @Named

There is a lot of discussions regarding differences between @ManagedBean and @Named annotations.  It appears that pretty much everyone is suggesting @Named as a best solution. As you can read, people say often that "...the presence of JSF 2 annotations is only to enable those on top of a Servlet containers ...".

I think this is not the whole truth.

Annotations from th package "javax.faces.bean" are provided for JSF managed beans where CDI annotations are helpers for CDI managed beans. Why I wrote JSF managed beans and CDI managed beans? Cause from the technical point of view JSF beans and CDI beans are completely separate entities. Managed bean is an object that it's life cycle is managed by a container. When JSF managed beans are managed by JSF container, CDI beans are managed by CDI container, and finally other types of beans (by example EJB) are managed by separate containers (by example EJB container) and so on.

Each container works independently. You could think about every container as a an independent process, which starts when server starts, scans loaded classes, gather and store some metadata about them, then when you need an object of a class at runtime they will give you instances of those classes and after finishing the job, they will destroy them.

So. We have different types of mananeged beans, and different types of managed bean containers. But which is "better" for typical JSF application?

The JSF managed beans are the part of JSF specifitacion from early 1.0 version, while the CDI container was introduced to the Java EE version 6.0 as a default, platform wide, managed beans framework. From this point of view you should use CDI where it is possible. CDI beans are far more advanced and flexible than simple JSF managed beans. With CDI you can use interceptors, conversation scope, events, type safe injection, decorators, stereotypes, producer methods and so on. In short words: as many says CDI is preferred over plain JSF because CDI allows for JavaEE-wide dependency injection. Of course if you need all this stuff.

But. There isn't any JSF managed beans advantage over CDI beans?

There are two simple issues which comes to my mind:

1. View Scope managed beans is a compelling reason to stick with JSF @ManagedBean - especially when you use a lot of AJAX requests. There is no standard replacement for this in CDI.
2. Efficiency is the next reason worth to consider. Especially if you work with Servlet container and CDI would be installed as an addition.

1 comment: