Refer Bean Scope | Reference Bean Scope |
Application | Application |
Session | Application, Session |
Request | Application, Session, Request |
Examlple :
We have two classes Managed_Bean_Class1 & Managed_Bean_Class2 ,
public Class Managed_Bean_Class1 {
private String userName;
public void setUserName( String userName){
this.userName = userName;
}
public String getUserName(){
return userName;
}
}
if we need the instance of Managed_Bean_Class1 in Managed_Bean_Class2
public Class Managed_Bean_Class2 {
private String dbURL;
public void setUserName(String dbURL){
this.dbURL = dbURL;
}
public String getUserName(){
return dbURL;
}
public boolean checkUser() {
/* Normal way */
Managed_Bean_Class1 ref = (Managed_Bean_Class1)FacesContext.getCurrentInstance()
.getApplication().createValueBinding("#{managed_Bean_Class1}")
.getValue(FacesContext.getCurrentInstance());
String userName = ref.getUserName();
............
// business logic
}
public boolean connect() {
........
........
}
}
faces-config.xml entries for Managed_Bean_Class1 & Managed_Bean_Class2
<managed-bean>
<managed-bean-name>managed_Bean_Class1</managed-bean-name>
<managed-bean-class>myproject.UserData</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>managed_Bean_Class2</managed-bean-name>
<managed-bean-class>myproject.Control</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
</managed-bean>
In case of dependency injection:
We have the Managed_Bean_Class1 as a property with getter & setter.
public Class Managed_Bean_Class2 {
private String dbURL;
public void setUserName(String dbURL){
this.dbURL = dbURL;
}
public String getUserName(){
return dbURL;
}
private Managed_Bean_Class1 class1_in_class2 = null;
public setClass1_in_class2(Managed_Bean_Class1 class1_in_class2){
this.class1_in_class2 = Class1_in_class2;
}
public Managed_Bean_Class1 getClass1_in_class2(){
return class1_in_class2;
}
public boolean checkUser() {
/* Normal way */
String userName = getClass1_in_class2().getUserName();
/* This will get the value in userName property
in Managed_Bean_Class1 */
............
// business logic
}
public boolean connect() {
........
........
}
}
faces-config.xml entries for Managed_Bean_Class1 & Managed_Bean_Class2:
<managed-bean>
<managed-bean-name>managed_Bean_Class1</managed-bean-name>
<managed-bean-class>myproject.UserData</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>managed_Bean_Class2</managed-bean-name>
<managed-bean-class>myproject.Control</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
<managed-property>
<property-name>class1_in_class2</property-name>
<value>#{managed_Bean_Class1}</value>
</managed-property>
</managed-bean>
Comments (0)
Post a Comment