Play Framework 2.0:自定义格式化程序

时间:2012-06-07 20:56:19

标签: java playframework-2.0

我正在尝试编写自定义格式化程序(对于DateTime字段,而不是java.util.Date字段),但我很难让它工作。我已经创建了我的注释,并扩展了AnnotationFormatter类。我在Application load上调用了play.data.format.Formatters.register(DateTime.class,new MyDateTimeAnnotationFormatter()),但是解析和打印方法永远不会触发。

我该怎么做?

编辑:相关代码可能会有所帮助;)

注释类(受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();

我在这里失去了。

2 个答案:

答案 0 :(得分:0)

您需要注册JodaDateTime而不是DateTime。

play.data.format.Formatters.register(JodaDateTime.class, new AnnotationDateTimeFormatter());

答案 1 :(得分:0)

我对DateTime的格式化程序有类似的问题。我正在Global.onStart注册格式化程序,如here所述。看来简单地创建Global类并没有触发重载。一旦我修改了另一个触发重新加载的文件(在控制台输出中显示为--- (RELOAD) ---),它就开始工作了。停止并重新启动您的应用应具有相同的效果。