How to inject a ManagedBean into a ManagedBean
Sonntag, 30. Mai 2010
That's really easy, just use the @ManagedProperty annotation.
A Simple Example:
We got two managed beans, one for logging into the system and storing the user's state, and one for using a shopping cart. We got the LoginController
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "loginController")
@SessionScoped
public class LoginController {
... // Do something...
}
and the ShoppingCartController, where we want to use the LoginController:
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class ShoppingCartController {
// Inject some Enterprise Java bean (has nothing to do with the example)
@EJB
private BookingBean bookingBean;
//Inject the LoginController (that's what we wanted to do )
@ManagedProperty("#{loginController}")
LoginController loginController;
... // do the shopping cart stuff
}
That is easy. If you know how :)
