Creating Named beans with annotations (JSF 2.0)

The named bean is a Context and Dependency Injection (CDI) object used in developing a JSF application. After you create a named bean, you can drag it from the Page Data view to use in JSF pages in the project. The named bean is also available through the content assist for EL expressions.

Before you begin

  1. Create a Facelet enabled Web project (JSF 2.0), and select JSF Version 2.0 and Add support JCDI from the JSF settings wizard.
  2. Create a Java™ package.
  3. Create a Java class.

Procedure

To make named bean accessible through the EL expressions:

  1. Double-click your Java class to open it in the editor.
  2. Add the following import statement below the package declaration: javax.inject.Named;.
  3. Add the @Named annotation before the public class definition. This annotation indicates that the class is a named bean.
  4. You can specify a name to the named bean by adding an argument to the @Named annotation. For example, @Named("myBean"). If no name is specified, the Java class name is used as the name by default, with the first character converted to lowercase characters.
  5. You can specify the scope for the named bean by using the following scope annotations:
    Option Description
    @ApplicationScoped Stores the bean during the application is active.
    @ConversationScoped Stores the bean during the conversation, provides state that is associated with a particular conversation.
    @Dependent Specifies that a bean belongs to the dependent scope, and no injected instance of the bean is shared.
    @NormalScoped Specifies that an annotation type is a normal scope type.
    @RequestScoped Stores the bean during the HTTP request.
    @SessionScoped Stores the bean during the session
  6. Add properties and other annotations to the class.

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

Results

The named bean class is displayed in the Page Data view under the Named Beans node.

What to do next

After you create a named bean, you can easily drag it from the Page Data view to reuse on other Facelet pages.

Feedback