Java Reference
In-Depth Information
A bean annotated with a scope holds state for the duration of the scope and shares that state with
any client that runs in the same scope. For example, a bean in the request scope holds state for the
lifetime of the HTTP request, and a bean with session scope holds state for the lifetime of the HTTP
session. The scoped bean is automatically created when it is needed and destroyed when the context
in which it takes part i nishes.
The scope annotations are often used to give scope to beans that are used via Expression Language
(EL) in Facelet pages.
Naming and EL
A bean annotated with @Named is accessible through EL. By default, the name used in the
expression is the name of the class with the i rst letter in lowercase. To refer to getter methods
that start with get or is , omit the get or is part of the method name. Listing 5‐11 shows an
example.
LISTING 5‐11 : The @Named annotation makes a bean visible to EL
package com.devchronicale.di;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
@Named // Defining that this is a managed bean
@RequestScoped // Defines the scope
public class User {
private String fullName;
public String getFullName(){
return this.fullName;
}
// some methods not included for brevity
}
This is a simple implementation of a named bean that returns a String when the getFullName()
method is called. In a Facelets page, you would refer to this method as user.fullname .
<h:form id="user">
<p><h:outputText value=" #{user.fullname} "/></p>
</h:form>
CDI Beans for Backing JSF
As in the previous example, CDI Beans can serve as backing beans for JSF pages. You can access
named beans via the name of the bean with a lowercased i rst letter. You can access Getter/Setter
i elds and methods within JSF pages using Java conventions. Details of JSF go beyond the scope of
this topic, but Listing 5‐11 demonstrates a basic usage of CDI Beans with JSF.
 
Search WWH ::




Custom Search