[英]Play Framework 2.0: Custom formatters
我正在尝试编写一个自定义格式化程序(对于DateTime字段,而不是java.util.Date字段),但我很难让它工作。 我已经创建了我的注释,并扩展了AnnotationFormatter类。 我在Application load上调用了play.data.format.Formatters.register(DateTime.class,new MyDateTimeAnnotationFormatter()),但是解析和print方法永远不会触发。
我该怎么做?
编辑:有问题的代码可能会有所帮助;)
注释类(受Play Framework附带的注释类的启发):
@Target({ FIELD })
@Retention(RUNTIME)
@play.data.Form.Display(name = "format.datetime", attributes = { "pattern" })
public static @interface JodaDateTime {
String pattern();
}
自定义格式化程序类:
public static class AnnotationDateTimeFormatter extends AnnotationFormatter<JodaDateTime, DateTime> {
@Override
public DateTime parse(JodaDateTime annotation, String text, Locale locale) throws ParseException {
if (text == null || text.trim().isEmpty()) {
return null;
}
return DateTimeFormat.forPattern(annotation.pattern()).withLocale(locale).parseDateTime(text);
}
@Override
public String print(JodaDateTime annotation, DateTime value, Locale locale) {
if (value == null) {
return null;
}
return value.toString(annotation.pattern(), locale);
}
要在框架中注册格式化程序,我在Application类的静态initalizer中进行此调用(可能有一个更好的地方放置它,随时告诉我在哪里):
play.data.format.Formatters.register(DateTime.class, new AnnotationDateTimeFormatter());
我已经通过调试器单步执行确认此调用已经完成并且没有抛出任何错误,但是仍然运行格式化程序,尽管如此适当地注释DateTime字段:
@Formats.JodaDateTime(pattern = "dd.MM.yyyy HH:mm:ss")
public DateTime timeOfRequest = new DateTime();
我在这里失落。
您需要注册JodaDateTime而不是DateTime。
play.data.format.Formatters.register(JodaDateTime.class, new AnnotationDateTimeFormatter());
我对DateTime
的格式化程序有类似的问题。 我是从我的注册格式化Global.onStart
描述这里 。 看起来简单地创建Global
类并没有触发重新加载。 一旦我修改了另一个触发重载的文件--- (RELOAD) ---
在控制台输出中显示为--- (RELOAD) ---
)它就开始工作了。 停止并重新启动您的应用应具有相同的效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.