Creating Faces managed beans with annotations (JSF 2.0)

To work with dynamic data on your Facelet page, you need to define a data source, such as a JavaBean. You can use @ManagedBean annotations to define a POJO as a managed bean so that the class is registered as a managed bean during runtime. @ManagedBean annotations can replace <managed-bean> entries in the faces-config.xml file, however, a managed bean declaration in the faces-config.xml file will override the annotation.

Procedure

  1. Double-click your Java class to open it in the editor.
  2. Add the following import statement below the package declaration : javax.faces.bean.ManagedBean;.
  3. Add the @ManagedBean annotation before the public class definition. This annotation indicates that the class is a managed bean.
  4. You can specify the name of the managed bean with the name property of the @ManagedBean annotation, for example @ManagedBean(name="myBean"). If no name is specified, the Java class name is used as the name by default, with the first character converted to lower case
  5. You can specify the scope for the managed bean using the following scope annotations:
    Option Description
    @RequestScoped Stores the bean for the duration of the HTTP request.
    @ViewScoped Stores the bean until the ID for the current view changes.
    @SessionScoped Stores the bean for the duration of the session
    @ApplicationScoped Stores the bean for the duration of the application.
    @NoneScoped The bean is instantiated each time it is referenced, and is not saved in any scope.
    @CustomScoped An EL expression that points to a map which controls the visibility and lifetime of beans.
  6. Add properties and other annotations to the class.

    The annotations are also visible in the Annotations view (Window > Show View > Other > Java > Annotations).

    For more information about annotations for managed beans, refer to the Faces Managed Bean Annotation Specification (2.0) .

Results

The bean class appears in the Page Data view under the Faces Managed Beans node.

What to do next

The managed beans you create can be used on any Facelet page in your project. Once you create a Faces managed bean, you can easily drag it from the Page Data view to reuse on other Facelet pages.

Feedback