开发者

Basics of Spring formatter service

Really basic question:

If I use Springs default formatters, how do I actually render a formatted string. Can someone help me complete the code example below, what goes in the ???:

@DateTimeFormat(pattern="yyyy-MMM-dd hh:mmaa");
DateTime myJodaDateTime = ...;

System.out.println( "How do I print myJodaDate开发者_运维问答Time, formatted: " + ??? );


It looks like annotation-configured formatters are intended to be used with object fields and method parameters only. Moreover, it looks like they forgot to provide convenient entry point to use these features manually. So, you can do something like this:

public class Foo {
    @DateTimeFormat(pattern="yyyy-MMM-dd hh:mmaa")
    DateTime myJodaDateTime = ...; 
}
...
ConversionService cs = ...; // FormattingConversionService with default formatters
System.out.println(
    cs.convert(
        foo.myJodaDateTime, 
        new TypeDescriptor(Foo.class.getDeclaredField("myJodaDateTime")),
        TypeDescriptor.valueOf(String.class)
    )
);

Alternatively, you can use

BeanPropertyBindingResult r = new BeanPropertyBindingResult(foo, "foo");
r.initConversion(cs);
System.out.println(r.getFieldValue("myJodaDateTime"));

but it looks as an abuse of databinding functionality.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜