January 16, 2021
Hot Topics:

Java Tip: Use EL Names to Access a Bean from Non-Java Code

  • By Leonard Anghel
  • Send Email »
  • More Articles »

You can reference a bean in non-Java code as long as the code supports unified expression language (EL) expressions. All you need to do is assign the bean an EL name. After you do that, the bean will be accessible from JSP and JSF pages, or any other context capable of understanding EL expressions.

You use the @Named annotation to indicate the EL name. This following annotation demonstrates this by calling a bean from non-Java code:

package com.mybeans;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

public class MyBean {

    private String email = "myemail@yahoo.com";

    //this is a business logic method
    public void checkEmail() {   //...   }

    //getter and setter methods for email property
    public String getEmail() {
        return email;

    public void setEmail(String email) {
        this.email = email;

Thanks to the @Named annotation, you can access the bean properties and business logic methods from a JSF page like this:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
        <title>Call a CDI bean</title>
        <h:form id="myForm">
            <p><h:outputLabel value="Press the button to call the bussines method ..."/></p>
            <p><h:commandButton value="Call checkEmail" action="#{myBean.checkEmail}"/></p>
            <p><h:outputText value="#{myBean.email}"/></p>

Without the @Named annotation, this bean is invisible to the JSF page.

Author Notes:

  1. You can also specify the bean name to be used, like this:
  2. Do not forget that an application that uses CDI must have a file named beans.xml (it can be empty, but it MUST be present).

Originally published on https://www.developer.com.

This article was originally published on February 4, 2011

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date