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

前端 未结 5 1295
故里飘歌
故里飘歌 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:50

    You could access it indirectly through FacesContext, which is a parameter in both Converter methods.

    The converter could be also annotated CDI Named with Application scope. When accessing the facade, two instances of the same class are used. One is the converter instance itself, dumb, without knowing EJB annotation. Another instance retains in application scope and could be accessed via the FacesContext. That instance is a Named object, thus it knows the EJB annotation. As everything is done in a single class, access could be kept protected.

    See the following example:

    @FacesConverter(forClass=Product.class)
    @Named
    @ApplicationScoped
    public class ProductConverter implements Converter{
        @EJB protected ProductFacade facade;
    
        protected ProductFacade getFacadeFromConverter(FacesContext ctx){
            if(facade==null){
                facade = ((ProductConverter) ctx.getApplication()
                    .evaluateExpressionGet(ctx,"#{productConverter}",ProductConverter.class))
                    .facade;
            }
            return facade;
        }
    
        @Override
        public Object getAsObject(FacesContext context, UIComponent component, String value) {
            return getFacadeFromConverter(context).find(Long.parseLong(value));
        }
    
    ...
    

提交回复
热议问题