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()
.
Note
To make this injection successful, the inject property (messageBean) must provide the setter method.