Reputation: 33
It is similar to @Inject is injecting a new instance every time i use it, but I cannot find answer in that thread.
I'm very new to both CDI and JSF, and I'm trying to use CDI instead of JSF annotations. I want to retrieve Credential from MemberController. The bean itself (both) are invoked from the jsf pages. The problem is the instance of Credential in MemberController always has null name/password, even I confirmed that the setter in Credential is hit. I don't understand why there are two instances of Credential. I could get what I want through @ManagedBean+@ManagedProperty. But I want to know how could I do the same thing with CDI.
My Environment is JBoss 7.1.1+Java EE 6
Credential.Java
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import java.io.Serializable;
@Named
@SessionScoped
public class Credential implements Serializable{
private static final long serialVersionUID = 680524601336349146L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String password;
}
MemberController.Java
@Named
@SessionScoped
public class MemberController implements Serializable {
private static final long serialVersionUID = 8993796595348082763L;
@Inject
private Credential newCredential;
public void login() {
String msg = newCredential.getName()+":"+newCredential.getPassword();
}
}
JSF page segment
<p:inputText id="username" label="Username" value="#{credential.name}" />
<p:password id="password" label="Password" value="#{credential.password}" />
<p:commandButton value="Login" action="members" actionListener="#{memberController.login}" />
Upvotes: 0
Views: 2383
Reputation: 159
The injection doesn't call a new instance (well the first time it's been called, or the injected bean has a requestscope). It is depending on the scope you use for your bean. The Scope you use will generate for each person using your application a new bean (their own sessionscope bean). The data inside this scope are only visible for this person. If you want a global container for your application which is accessible by all users of your application, containing the same data for everyone, you should create a applicationscope or a singelton bean. With this annotations you create one container accessible for everybody during the lifetime of your application, as a central point for holding data.
Upvotes: 1