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.