Injecting Managed beans in JSF 2.0
In JSF 2.0, a new @ManagedProperty annotation is used to dependency injection (DI) a managed bean into the property of another managed bean.
Let see a @ManagedProperty example :
MessageBean.java – A managed bean named “message“.
import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name="message") @SessionScoped public class MessageBean implements Serializable { //business logic and whatever methods... }
HelloBean.java – Inject the “message” bean into the “messageBean” property.
import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; @ManagedBean @SessionScoped public class HelloBean implements Serializable { @ManagedProperty(value="#{message}") private MessageBean messageBean; //must povide the setter method public void setMessageBean(MessageBean messageBean) { this.messageBean = messageBean; } //... }
In this example, it uses the @ManagedProperty annotation to DI the “message” bean (MessageBean.java) into the property (messageBean) of the “hello” bean (HelloBean.java) via setter method, setMessageBean().
To make this injection successful, the inject property (messageBean) must provide the setter method.
Download Source Code
Reference
- ManagedProperty Javadoc
- JSF 2.0 : managed bean x does not exist, Check that appropriate getter and/or setter methods exist
IF there is no message bean instance does jsf create it not any annotation force to create?
THis was very useful to me. Thank you very much.
instead of @ManagedBean(name=”message”), can I use @Named(“message”)?
Note: JSF2 introduced the @ManagedBean annotation which was intended to minimise Faces configuration in XML files. Whilst this alleviates the need to declare JSF managed beans in XML it does not promote annotation consistency across all layers in the application.
it i good job.Thanks mkyong.
I agree with mkyong,
there is no problem of using sessionScoped, especially in a simple example like this.
If you have a large application and you keep using sessionScoped for all your beans than you should rethink your design.
Whats wrong with sessionscoped?
ohh man! do you use sessionScoped? shame on you!
hi bro, i have ntg to shame for, it’s just one of the way to do DI in JSF. Please share your code and experience
This is just an example. I used that for View Scoped and it worked fine. Please don’t condemn others work like this.