HTML and CSS Reference
In-Depth Information
Accessing Managed Beans from Java Code
It is important to know how to access managed beans from the Java code. This is useful if you want to get the
information of a specific managed bean (for example
bean1
) from another managed bean (for example
bean2
)
that is not referring to
bean1
directly. In order to access managed beans from the Java code, you need to use the
ValueExpression
class. Listing 2-13 shows how to get the information of the
User
managed bean from the Java code.
Listing 2-13.
Getting the User Managed Bean Information from the Java Code
FacesContext context = FacesContext.getCurrentInstance();
Application application = context.getApplication();
ELContext elContext = context.getELContext();
ExpressionFactory expressionFactory = application.getExpressionFactory();
ValueExpression valueExpression = expressionFactory.createValueExpression
(elContext, "#{user}", User.class);
User user = (User) valueExpression.getValue(elContext);
In order to retrieve the
User
managed bean information, a
ValueExpression
object is created using the
createValueExpression
API of the
ExpressionFactory
class. The
createValueExpression
API takes the following
arguments:
•
ELContext
, which refers to the EL context used to parse the expression.
The expression String to parse.
•
•
The type that the result of the expression will be coerced to after the expression evaluation.
Using the
ValueExpression
object, you can get the value of the expression using the
getValue(ELContext)
API, and you can also use the
ValueExpression
object for setting a value to the expression in the runtime using the
setValue(ELContext
,
value)
API.
@Named and @inject Annotations
In future JSF specifications, the
@ManagedBean
will be deprecated so it is recommended to use the
@Named
CDI
(Context and Dependency Injection) annotation instead of the
@ManagedBean
. You should know that the
@ManagedBean
is managed by the JSF framework, while the
@Named
annotation is not managed by the JSF framework. The
@Named
annotation is managed by the JEE application server which supports CDI. One advantage of the CDI over the JSF
dependency injection is that in order to inject an instance using the CDI
@inject
annotation, this instance does not
require to be annotated with any specific annotation, while in JSF, the
@ManagedProperty
requires the bean to be
injected to be annotated with the
@ManagedBean
annotation.
Let's see how we can use the
@Named
annotation for the
User
managed bean instead of the
@ManagedBean
. Listing 2-14
shows the modified version of the
User
managed bean that utilizes the
@Named
annotation.
Listing 2-14.
The @Named User Managed Bean
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;