@FacesConverter 没有 converter-id 和 forClass

@FacesConverter without converter-id and forClass

如果我在确定@FacesConverter 注解时没有指定converter-id 和(或)forClass,应该怎样才能正常工作? 例如:

@FacesConverter
public class SplitConverter implements Converter{

@Override
public Object getAsObject(FacesContext context, UIComponent component,
        String value) {
    //...
}
@Override
public String getAsString(FacesContext context, UIComponent component,
        Object value) {
    //...

} 

在 faces-config.xml 中注册并在 .xhtml 页面上使用后:

<h:inputText id="badges" value="#{article.badges}" 
    required="true">
    <f:converter converterId="com.katcgr.SplitConverter" />
</h:inputText>

一切都是工作。文档说

if converter-id is the empty string, Application.addConverter(java.lang.Class,java.lang.String) is called, passing the converter-for-class as the first argument and the derived converter-class as the second argument.

但为什么即使我没有指定 forClass 也一切正常?

After registred in faces-config.xml

通过 @FacesConverterfaces-config.xml 中的 <converter> 注册是互斥的,因此 XML 注册 覆盖 任何注解注册。因此,当通过在 XML 中注册的转换器 ID 引用您的转换器时,转换器实例的行为基本上就好像它没有注释一样。如果您删除 XML 注册,那么您应该在指定的 converterId:

上检索到以下异常
javax.faces.FacesException: Expression Error: Named Object: com.katcgr.SplitConverter not found.
    at com.sun.faces.application.ApplicationImpl.createConverter(ApplicationImpl.java:1339)
    at javax.faces.application.ApplicationWrapper.createConverter(ApplicationWrapper.java:393)
    at com.sun.faces.facelets.tag.jsf.ConverterTagHandlerDelegateImpl.createConverter(ConverterTagHandlerDelegateImpl.java:158)
    ...

这基本上只有在您有

@FacesConverter("com.katcgr.SplitConverter")

如果您同时删除 XML 配置和 <f:converter>,那么它将 "work" 因为没有显式 forClass@FacesConverter 将是为每个 bean 属性 自动调用,它是 java.lang.Object 的一个实例(基本上,所有东西),它没有已经注册的更具体的转换器。换句话说,您的转换器将表现为:

@FacesConverter(forClass=Object.class)

希望不需要详细解释这是一个非常糟糕的主意。它还会混淆 PrimeFaces,因为它将在内部初始化并将其用作 String class.

的默认转换器