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

I started web development with JSF, after learning JSP and Servlets for a while.

When you create a JSF web application, you always (maybe often, but I'm not sure whether it is always or not) create beans.xml and you don't write anything in it. But if this file does not exist, the JSF web application will not work.

What is the reason for this?

Why do we need this file?

Please have a detailed explanation.

+4
source share
3 answers

Addendum to Micah's answer; CDI is not only useful in combination with JSF because of the support for injection, but also because of its support, which must be used with EL (expression language). This feature of JSF is highly dependent on.

In fact, CDI beans can almost completely replace JSF managed beans, and so you will find many examples using them, and a large number of JSF books that advise you to use them. For JSF applications, CDI beans have, for example, the following advantages:

  • May introduce smaller areas to larger areas. For instance. GET request parameters with the request can be entered into the bean session zone. This is not possible with JSF managed beans.
  • Can use the conversation area; An area that spawns several different pages.

It is unfortunate that in JSF 2.0 and 2.1 the extremely convenient viewing area is not supported by default CDI beans, although extensions such as Seam can add them. (update: in JSF 2.2 there is a new viewport that works with CDI beans)

In general, the confusion between JSF Managed beans and CDI beans is such that there is a JSF specification for it, see http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-976

+3
source

The presence of the beans.xml file signals the servlet container that the application is using JSR-299 (Contexts and dependency injection) - without it, application classes will not be scanned for CDI annotations, and no other injection will be performed. If you are not using CDI (for example, using only the simple beans JSF interface), you do not need beans.xml. If you do this, you can use the file (instead of annotations) to define CDI configurations - this allows you, for example, to provide a test configuration in which some dependencies are replaced with mocks.

+4
source

From Getting Started with Injection and JSF 2.x Contexts and Dependencies

When deploying the application, the server searches for managed CDI beans. In a Java EE 7 application, classes are scanned along the way for CDI annotations by default. In a Java EE 6 application, classes are scanned for CDI annotations if the module contains a beans.xml file.

0
source

All Articles