我正在尝试让自定义格式化程序在 Spring MVC 中工作。我看过一些关于此的帖子,包括:Custom Annotation-driven Formatting Spring MVC。我已经跟踪了我的应用程序,并且我知道格式化程序正在被注册。由于我确信格式化程序已注册,我认为它的注释被忽略了,但我不知道为什么。
以下是我注册格式化程序工厂的方式供参考:
@Override
public void addFormatters(FormatterRegistry registry)
{
registry.addFormatterForFieldAnnotation(new PhoneNumberFormatAnnotationFormatterFactory());
}
注解:
@Target(value = { ElementType.FIELD })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface PhoneNumber
{
}
格式化工厂:
public class PhoneNumberFormatAnnotationFormatterFactory implements AnnotationFormatterFactory<PhoneNumber>
{
@Override
public Set<Class<?>> getFieldTypes()
{
Set<Class<?>> setTypes = new HashSet<Class<?>>();
// setTypes.add(String.class);
setTypes.add(PhoneNumber.class);
return setTypes;
}
@Override
public Printer<?> getPrinter(PhoneNumber annotation, Class<?> fieldType)
{
return new PhoneNumberFormatter();
}
@Override
public Parser<?> getParser(PhoneNumber annotation, Class<?> fieldType)
{
return new PhoneNumberFormatter();
}
}
格式化程序:
public class PhoneNumberFormatter implements Formatter<String>
{
private static final Logger logger = Logger.getLogger(PhoneNumberFormatter.class);
@Override
public String print(String subject, Locale locale)
{
logger.debug("formatting phone number");
return subject + "BOO";
}
@Override
public String parse(String text, Locale locale) throws ParseException
{
return text;
}
}
视图中的用法:
<tr>
<td>Phone:</td>
<td>${workOrderDetailBean.subscriberPhone}</td>
</tr>