Inject JSF Managed Bean
This tutorial show how to inject JSF Managed Bean into another JSF Managed bean. In JSF 2.0 there is a new @ManagedProperty
annotation. This annotation is used for dependency injection. We can Inject a managed property into another managed bean.
- You cannot inject a CDI managed bean into a JSF managed bean.
- You cannot inject a JSF managed bean which scope is minor then the injecting bean. (with CDI you can).
Creating a JSF Backing Bean
We are defining a JSF managed bean that’ll be injected.
package com.memorynotfound;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
@ManagedBean
@SessionScoped
public class MessageBean implements Serializable {
public String getMessage(String name){
return "Hello, " + name;
}
}
Inject JSF Managed Bean
We use the @ManagedProperty
to inject a JSF managed bean. The setter method is important here. This setter method is used by the @ManagedProperty
to inject the managed bean. If you don’t have a setter method, the dependency injection will not work.
package com.memorynotfound;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
@ManagedBean
@SessionScoped
public class UserBean implements Serializable {
@ManagedProperty(value = "#{messageBean}")
private MessageBean messageBean;
public MessageBean getMessageBean() {
return messageBean;
}
// setter must be present or managed property won't work
public void setMessageBean(MessageBean messageBean) {
this.messageBean = messageBean;
}
}