Some people have wondered why CDI requires an explicit @Named annotation before a bean can be accessed using EL? Why not just give all beans names by default?

Well, the reason is that EL has a single flat namespace. There's no notion of qualified names in EL. Experience in the JSF community is that avoiding duplicate names is harder than it looks, especially when the application includes multiple modules maintained by different teams. Remember that not all CDI beans are intended to form part of the user interface layer. A Java EE 6 application might include modules defining an independent business layer, whose beans should always be accessed via typesafe dependency injection instead of non-typesafe EL names. Beans in these modules should not have EL names, in order to avoid polluting the namespace of the UI layer.

Still, the combination @Named @RequestScoped is going to be super-common in JSF applications. So CDI includes a built-in stereotype that encapsulates these defaults. The @Model stereotype refers to the M role in the MVC pattern. We recommend that all JSF user-interface-oriented beans be annotated @Model to both save a little typing (one annotation instead of two), and, more importantly, to make clear their architectural role in the system.

Indeed, even when you have a UI model bean that's not @RequestScoped, I recommend annotating it @ConversationScoped @Model rather than @Named @ConversationScoped. The two options have the same functional effect, but the first combination communicates more information to someone reading your code later, and makes it easy to quickly search for all UI model beans.

(Of course, if, for whatever reason, you don't like @Model, you can always define your own stereotype to fulfil a similar purpose. The CDI container doesn't treat @Model in any special way.)


Back to top