UI-Component Sets

Home » Wiki » MyFaces Core » MyFaces Core User Guide » JSF and MyFaces Howtos » Backend

Accessing one managed bean from another

How can I access one Managed Bean from another?

There are two ways for one managed bean to access another managed bean in the same webapp:

Using Dependency Injection

Using JSF 2 @ManagedProperty annotation

In your managed bean add a @ManagedProperty annotation to the related property and don't forget to add getter and setter methods.

public class UsingBean 

    private NeededBean neededBean;

    public NeededBean getNeededBean()
    return neededBean;

    public void setNeededBean(NeededBean neededBean)
    this.neededBean = neededBean;

    // ....


Binding through faces-config.xml

In your project's faces configuration file which defines the managed beans, a managed bean property can be declared as initialised with a reference to another managed bean:



The constraints are that:

  • the using bean must have scope which is the same as or shorter than the needed bean
  • the using bean must have a property-setter method which takes the needed bean as a parameter
  • the beans cannot have managed dependencies on each other.

Using Lookup

The following java code can be used in MyFaces 1.1 to explicitly look up an arbitrary managed bean by name:

FacesContext facesContext = FacesContext.getCurrentInstance();
NeededBean neededBean
    = (NeededBean) facesContext.getApplication()
    .getVariableResolver().resolveVariable(facesContext, "neededBean");

In MyFaces 1.2, that code is deprecated, and preffered version is:

ELContext elContext = FacesContext.getCurrentInstance().getELContext();
NeededBean neededBean 
    = (NeededBean) FacesContext.getCurrentInstance().getApplication()
    .getELResolver().getValue(elContext, null, "neededBean");

Alternately, you can use this code to evaluate any JSF EL expression.

FacesContext facesContext = FacesContext.getCurrentInstance();
NeededBean neededBean
    = (NeededBean)facesContext.getApplication()