How to inject in @FacesValidator with @EJB, @PersistenceContext, @Inject, @Autowired

痴心易碎 提交于 2019-11-25 22:32:03
BalusC

The @FacesValidator isn't managed by the injection container. You need to make it a managed bean. Use Spring's @Component, CDI's @Named or JSF's @ManagedBean instead of @FacesValidator in order to make it a managed bean and thus eligible for dependency injection.

E.g., assuming that you want to use JSF's @ManagedBean:

@ManagedBean
@RequestScoped
public class EmailExistValidator implements Validator {
    // ...
}

You also need to reference it as a managed bean by #{name} in EL instead of as a validator ID in hardcoded string. Thus, so

<h:inputText ... validator="#{emailExistValidator.validate}" />

or

<f:validator binding="#{emailExistValidator}" />

instead of

<h:inputText ... validator="emailExistValidator" />

or

<f:validator validatorId="emailExistValidator" />

This is indeed awkward. The JSF guys have confirmed this embarrassing oversight and they will make the @FacesValidator (and @FacesConverter) an eligible injection target in upcoming JSF 2.2 2.3, see also JSF spec issue 763. For EJBs there's a workaround by manually grabbing it from JNDI, see also Getting an @EJB in @FacesConverter and @FacesValidator. If you happen to use the CDI extension MyFaces CODI, then you can also solve it by putting @Advanced annotation on the class.

See also:


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 @FacesValidator class without any additional configuration or annotations. See also the CDI @FacesValidator showcase example.

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