Saturday, 1 March 2014

Injecting Beans in JSF 2.0

Here we will see how to inject managed bean in another bean using @ManagedProperty.

Firstly lets create a managed bean named "SupportBean.java".
SupportBean.java
package org.mani.beans;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

/**
 *
 * @author mani
 */
@ManagedBean(name="supportBean")
@SessionScoped
public class SupportBean implements Serializable {
 
 //business logic and methods come here...
 
}

Now we will create a HelloBean.java and will inject SupportBean in it.
HelloBean.java
package org.mani.beans;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
 
/**
 *
 * @author mani
 */
@ManagedBean
@SessionScoped
public class HelloBean implements Serializable {
 
 @ManagedProperty(value="#{supportBean}")
 private SupportBean supportBean;
 
 //must povide the setter method
 public void setSupportBean(SupportBean supportBean) {
  this.supportBean = supportBean;
 }
 
 //...
}

Here we have used @ManagedProperty for injecting into our local supportBean with the managedBean. Besides this,there are some other ways also through which we can inject managed beans into each other,will explore them later.