【问题标题】:Play Framework 2.0: Custom formattersPlay Framework 2.0:自定义格式化程序
【发布时间】:2012-06-07 20:56:19
【问题描述】:

我正在尝试编写一个自定义格式化程序(用于 DateTime 字段,而不是 java.util.Date 字段),但很难让它工作。我已经创建了注释,并扩展了 AnnotationFormatter 类。我在应用程序加载时调用 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 类的静态初始化程序中进行了这个调用(可能有更好的地方放置它,请随时告诉我在哪里):

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

我已经通过调试器单步执行了此调用并且没有引发错误,但尽管像这样适当地注释了 DateTime 字段,格式化程序仍然没有运行:

@Formats.JodaDateTime(pattern = "dd.MM.yyyy HH:mm:ss")
public DateTime timeOfRequest = new DateTime();

我在这里不知所措。

【问题讨论】:

  • 也许你可以发布你的代码?
  • 我确实可以。 :) 我编辑了我的原始帖子以包含有问题的代码。
  • 你解决了吗?

标签: java playframework-2.0


【解决方案1】:

您需要注册 JodaDateTime 而不是 DateTime。

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

【讨论】:

  • 这是不正确的。 register 的第一个参数必须是 AnnotationFormatter.parse 返回的类型。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 2016-11-30
    • 2012-06-17
    • 2023-02-08
    • 2014-02-15
    相关资源
    最近更新 更多