Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need beans.xml while working with JSF web application?

I started web development using JSF, after studying JSP and Servlets for a while.

When you create a JSF web application you always(may be often but I am not sure if it always or not) have to create beans.xml and you don't write anything in it. But, if that file doesn't exist the JSF web app will not work.

What is the reason behind that?

Why we need that file?

Please, detailed explanation.

like image 712
matiman Avatar asked May 29 '11 20:05

matiman


2 Answers

Adding to the answer of Micheal; CDI is not only useful in combination with JSF because of the injection support, but also because of its support to be used with EL (expression language). This is a feature JSF heavily depends upon.

In fact, CDI beans can almost entirely replace JSF managed beans and therefor you'll find lots of examples using them and a good amount of JSF books advising their use. For JSF applications CDI beans have e.g. the following advantages:

  1. Can inject smaller scopes into larger scopes. E.g. request scoped GET parameters can be injected into a session scoped bean. This is not possible with JSF managed beans.
  2. Can take advantage of the conversation scope; a scope that spawns multiple different pages.

Very unfortunate is that in JSF 2.0 and 2.1 the extremely handy view scope is not supported by CDI beans by default, although extensions like Seam can add these. (update: in JSF 2.2 there's a new view scope that does work with CDI beans)

All in all the confusion between JSF Managed beans and CDI beans is such that there's a JSF spec issue for this, see http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-976

like image 172
Arjan Tijms Avatar answered Sep 20 '22 00:09

Arjan Tijms


The presence of a beans.xml file signals the servlet container that the application uses JSR-299 (Contexts and Dependency Injection) - without it, the application's classes will not be scanned for CDI annotations either and dependency injection will not be performed. If you don't use CDI (e.g. you only use plain JSF managed beans), you don't need beans.xml. If you do, you can use the file (instead of annotations) to define CDI configurations - this allows you, for example, to provide a test configuration where some dependencies are replaced with mocks.

like image 45
Michael Borgwardt Avatar answered Sep 18 '22 00:09

Michael Borgwardt