<1> 使用依赖注入
在定义managed beans的faces配置文件中,一个managed bean可以作为另一个managed bean的初始化属性:
xml 代码
- <managed-bean>
- <managed-bean-name>neededBean<!---->managed-bean-name>
- <managed-bean-class>fqn.to.NeededBean<!---->managed-bean-class>
- <managed-bean-scope>session<!---->managed-bean-scope>
- managed-bean>
-
- <managed-bean>
- <managed-bean-name>usingBean<!---->managed-bean-name>
- <managed-bean-class>fqn.to.UsingBean<!---->managed-bean-class>
- <managed-bean-scope>request<!---->managed-bean-scope>
- <managed-property>
- <property-name>neededBean<!---->property-name>
- <value>#{neededBean}<!---->value>
- <<!---->managed-property>
- <<!---->managed-bean>
下面是一些制约因数:
- using bean的生命周期必须等于或小于needed bean的生命周期
-
using bean中必须将needed bean作为一个参数且有相应的setter方法
-
它们之间不能有管理的依赖
<2> 使用Lookup
下面的代码即可找到neededBean:
java 代码
- FacesContext facesContext = FacesContext.getCurrentInstance();
- NeededBean neededBean = (NeededBean) facesContext.getApplication()
- .getVariableResolver().resolveVariable(facesContext, "neededBean");
也可以这样,使用EL表达式:
java 代码
- FacesContext facesContext = FacesContext.getCurrentInstance();
- NeededBean neededBean = (NeededBean)facesContext.getApplication()
- .createValueBinding("#{neededBean}").getValue(facesContext);