JSF 2.3 中@FacesConverter 和@FacesValidator 中的 EJB 和托管 bean 注入

EJB and managed bean injections in @FacesConverter and @FacesValidator in JSF 2.3

@FacesConverter@FacesValidator 不符合 EJB 或 JSF 2.2 之前的托管 bean 注入点的条件。

它们应该与 JSF 2.3 一起工作(目前可作为 milestone only) using an additional managed attribute with @FacesConverter and @FacesValidator as mentioned here

In JSF 2.1 very few JSF artifacts were injection targets. In JSF 2.2 injection was made possible in a huge amount of additional artefacts but the very ones where injection actually matters most, converters and validators, were mysteriously left in the cold.

In JSF 2.3 this has now finally been taken care of as the following artefacts have been added to the list of injection targets:

  • javax.faces.convert.Converter
  • javax.faces.validator.Validator
  • javax.faces.component.behavior.Behavior

However, in contrast to the artefacts already on this list these new 3 are not automatically injection targets. They will only become so when a new attribute called "managed" on the corresponding annotations @FacesConverter, @FacesValidator and @Behavior is set to true. Furthermore all these 3 annotations have been upgraded to being CDI qualifiers by adding the @Qualified annotation to their definition.

The existing attributes of @FacesConverter, @FacesValidator and @Behavior have not been modified, meaning they are all binding, as is the new attribute "managed".

但是属性 managed 在 Mojarra 2.3.0-m02 中不可用。

是因为一个里程碑吗?它取决于特定的 Weld/CDI 版本吗?我目前正在使用 GlassFish Server 4.1。提到了不同的工件版本here(服务器版本提供的默认Weld版本是2.2.2 final)。

正如您在 Mojarra 2.3.0-m02 的 Application#createConverter() implementation, it checks if it's running in JSF 2.3 mode 中看到的那样,在尝试获取 CDI 管理的声明之前,根据 faces-config.xml version 声明。

换句话说,为了使 @FacesConverter(managed=true)@FacesValidator(managed=true) 以及 类 中的 @Inject 正常工作,您需要确保您的网络应用程序的 faces-config.xml 声明符合 JSF 2.3,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_3.xsd"
    version="2.3">

    <!-- Config here. -->

</faces-config>

请注意 JSF 2.3 XSD 文件中的 IDE 可能会出错(尚未公开),您可以安全地忽略该部分,它不会在运行时由 JSF 验证.您也可以坚持使用 2.2 XSD 并在不受支持的 version.

上忽略任何 IDE warning/error

jdevelopment.nl 博客作者已收到有关此事的通知,他将确保在下一次更新中在博客中阐明上述内容。