How to inject @EJB, @PersistenceContext, @Inject, @Autowired, etc in @FacesConverter?

前端 未结 5 1248
故里飘歌
故里飘歌 2020-11-22 13:04

How can I inject a dependency like @EJB, @PersistenceContext, @Inject, @AutoWired, etc in a @FacesConverter?

5条回答
  •  情歌与酒
    2020-11-22 13:51

    By Luis Chacon, Sv

    Works fine, tested

    definition EJB :

    @Stateless
    @LocalBean
    public class RubroEJB {
    
        @PersistenceContext(unitName = "xxxxx")
        private EntityManager em;
    
        public List getAllCfgRubroPres(){
            List rubros = null;
            Query q = em.createNamedQuery("xxxxxxx");
            rubros = q.getResultList();
            return rubros;
        }
    }
    

    define bean with the Aplication bean scope, for get the EJB Object

    @ManagedBean(name="cuentaPresService", eager = true)
    @ApplicationScoped
    public class CuentaPresService {
    
        @EJB
        private RubroEJB cfgCuentaEJB;
    
        public RubroEJB getCfgCuentaEJB() {
            return cfgCuentaEJB;
        }
    
        public void setCfgCuentaEJB(RubroEJB cfgCuentaEJB) {
            this.cfgCuentaEJB = cfgCuentaEJB;
        }
    }
    

    final Access to Ejb Object from Converter:

    @FacesConverter("cuentaPresConverter")
    public class CuentaPresConverter implements Converter {
    
        @EJB
        RubroEJB rubroEJB;
    
        public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
            if(value != null && value.trim().length() > 0) {
                try {
                    CuentaPresService service = (CuentaPresService) fc.getExternalContext().getApplicationMap().get("cuentaPresService");
    
    
                    List listCuentas=service.getCfgCuentaEJB().getAllCfgCuentaPres();
    
    
                    ................
    

提交回复
热议问题