CDI Injection into a FacesConverter

纵然是瞬间 提交于 2019-11-26 16:08:15

Replace

@FacesConverter(value = "categoryConverter")

by

@Named

and use

<h:inputSomething converter="#{categoryConverter}" />

or

<f:converter binding="#{categoryConverter}" />

instead of

<h:inputSomething converter="categoryConverter" />

or

<f:converter converterId="categoryConverter" />

By the way, similar problem exist for @EJB inside a @FacesConverter. It however offers a way to be grabbed by JNDI manually. See also Communication in JSF 2.0 - Getting an EJB in @FacesConverter and @FacesValidator. This way you can use a @FacesConverter(forClass=Category.class) without manually defining it everytime. Unfortunately I can't tell from top of head how to realize that for CDI beans.


Update: if you happen to use JSF utility library OmniFaces, since version 1.6 is adds transparent support for using @Inject and @EJB in a @FacesConverter class without any additional configuration or annotations. See also the CDI @FacesConverter showcase example.

Surprised Coconut

The @Inject Annotation only works in CDI managed instances. If you want to use CDI features inside a non-CDI managed instance (Like a JSF Validator or a JSF Converter) you can just programm against the CDI API.

This works only in at least Java EE 7 + CDI 1.1 server.

@FacesValidator("userNameValidator")
public class UserNameValidator implements Validator {

    private UserService userService;

    public UserNameValidator(){
        this.userService = CDI.current().select(UserService.class).get();
    }

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
     ....
    }
}

https://docs.oracle.com/javaee/7/api/javax/enterprise/inject/spi/CDI.html

With all the AnnotationHell in Java EE people forget how to code.

Dar Whi

Just use @Advanced of CODI for your @FacesConverter see the Wiki.

As soon as a converter or a validator is annotated with @Advanced it's possible to use @Inject.

Howard

Per BalusC's answer here, I decided to add JSF (requestscoped) managed beans that only contained @FacesConverter and Converter to resolve this issue in my app, since I'm migrating from JSF managed beans to CDI managed beans.

I tried CODI @Advanced against @FacesConverter, but it does not inject the bean at all.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!