I try to achieve resource injection for a long time but couldn't succeeded.
I use JSF 2.2, JDK 1.7. And my ide is eclipse luna.
I have a session scoped bean called UserBean and view scoped bean called SettingsBean.
I set them in faces-config.xml UserBean as session scoped and SettingsBean as view scoped with their bean name "settingsBean" and "userBean"
public class SettingsBean implements Serializable {
private static final long serialVersionUID = 1L;
@Inject // I also tried @ManagedProperty but didn't work
private UserBean userBean;
@PostConstruct
public void init(){
System.out.println(userBean.getUser().getFullName());
}
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
}
The problem is I get userBean as null. What is the problem here? Thanks for help.
I removed ManagedBean and ViewScoped definitions in faces-config.xml for settingsBean and added them in SettingsBean.java file manually.
And added this also:
@ManagedProperty(value="#{userBean}")
private UserBean userBean;
So finally, it works:
@ManagedBean
@ViewScoped
public class SettingsBean implements Serializable{
private static final long serialVersionUID = 1L;
@ManagedProperty(value="#{userBean}")
private UserBean userBean;
//...
@PostConstruct
public void init(){
System.out.println(userBean.getUser().getFullName());
}
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With