我有以下ApplicationScoped bean
package es.caib.gesma.gesman.data;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import es.caib.gesma.gesman.ejb.Dao;
@ManagedBean(name="priorityList")
@ApplicationScoped
public class PriorityList {
@EJB
Dao daoEjb;
private List<Priority> priorities = null;
public PriorityList() {
}
@PostConstruct
public void refresh() {
this.priorities = daoEjb.findPriorities();
}
public List<Priority> getPriorities() {
return this.priorities;
}
public Priority fromId(int id) {
for(Priority priority : this.priorities) {
if (priority.getId() == id) {
return priority;
}
}
return null;
}
}
我尝试将该bean注入Converter
package es.caib.gesma.gesman.data.converter;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import es.caib.gesma.gesman.data.Priority;
import es.caib.gesma.gesman.data.PriorityList;
@ManagedBean
@ApplicationScoped
public class PriorityConverter implements Converter {
@ManagedProperty("#{priorityList}")
private PriorityList priorityList;
@Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
...
}
@Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
...
}
public void setPriorityList(PriorityList priorityList) {
System.out.println("SET PRIORITYLIST " + priorityList);
this.priorityList = priorityList;
}
}
每当我尝试访问该属性时,它都为null。永远不会调用setter。
从this question和this one,看起来不可能以通常的方式注入bean(如果我错了请纠正我)。还有其他选择,所以我不必每次都从EJB(=数据库访问)获取整个值列表吗?
答案 0 :(得分:1)
您不能(当前)将依赖项注入转换器。但是,如果您可以使用Seam 3,则seam-faces模块将启用此功能。你不需要做任何特殊的事情,只需在类路径中使用缝面JAR(及其任何依赖项)并注入转换器就会神奇地工作。请注意其他非预期的副作用(我注意到当接缝持久性JAR在类路径中时,事务边界存在差异)。
答案 1 :(得分:0)
我认为你应该可以从HttpSession中取出这个bean(它适用于带有SessionScoped bean的PhaseListener)
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
SessionForm sessionBean = (SessionForm) session.getAttribute("priorityList");
或者如果我可以从BalusC借用关于JSF communication的文章,在底部描述了如何从ManagedBean创建一个转换器(这样你就可以轻松地在那里注入你的ApplicationScoped bean)