Access one Managed Bean from another in JSF 2.0 | Techartifact

Requirement- Access one Managed Bean from another in JSF

Solution- There are two ways-

Dependency Injection

We can use JSF 2 @ManagedProperty annotation

In the managed bean add a @ManagedProperty annotation to the related property

@ManagedBean(name="currentBean")
@RequestScoped
public class CurrentBean 
{

    @ManagedProperty(value="#{requiredBean}")
    private RequiredBean requiredBean;

    public RequiredBean getRequiredBean()
    {
        return requiredBean;
    }

    public void setRequiredBean(RequiredBean requiredBean)
    {
        this.requiredBean= requiredBean;
    }

    // ....


}

Usingthrough faces-config.xml

<managed-bean>
   <managed-bean-name>requiredbBean</managed-bean-name>
   <managed-bean-class>vinay.common.RequiredBean</managed-bean-class>
   <managed-bean-scope>session</managed-bean-scope>
 </managed-bean>

 <managed-bean>
   <managed-bean-name>currentBean</managed-bean-name>
   <managed-bean-class>vinay.common.CurrentBean</managed-bean-class>
   <managed-bean-scope>request</managed-bean-scope>
   <managed-property>
     <property-name>requiredbBean</property-name>
     <value>#{requiredbBean}</value>
   </managed-property>
 </managed-bean>

Following are the constraints:

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

Vinay

I am an Oracle ACE in Oracle ADF/Webcenter. Sr Java Consultant-working on Java/J2EE/Oracle ADF/Webcenter Portal/ content and Hibernate for several years. I'm an active member of the OTN JDeveloper/Webcenter forum. Passionate about learning new technologies. I am here to share my knowledge. Give your views and suggestion on [email protected] .

More Posts - Website

Follow Me:
TwitterLinkedInGoogle PlusYouTube