Spring Formatters配置选项

时间:2015-01-09 13:41:52

标签: java spring

Spring格式化程序的以下配置之间是否存在差异?

配置1)

public class AppConfigurator extends WebMvcConfigurerAdapter {
.....
@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addFormatter(new DateFormatter());
}

配置2)

public class AppConfigurator extends WebMvcConfigurerAdapter {
.....
@Bean
public FormattingConversionServiceFactoryBean conversionService(){
    FormattingConversionServiceFactoryBean formattingConversionServiceFactoryBean = new FormattingConversionServiceFactoryBean();
    Set<Formatter<?>> formatters = new HashSet<>();
    formatters.add(new DateFormatter());
    formattingConversionServiceFactoryBean.setFormatters(formatters);
    return formattingConversionServiceFactoryBean;
}

附录:

(自定义创建的java.util.Date DateFormatter.class格式化程序)

public class DateFormatter implements Formatter<Date> {

public DateFormatter() {
    super();
}

@Override
public String print(Date object, Locale locale) {
    final SimpleDateFormat dateFormat = createDateFormat();
    return dateFormat.format(object);
}

@Override
public Date parse(String text, Locale locale) throws ParseException {
     final SimpleDateFormat dateFormat = createDateFormat();
       return dateFormat.parse(text);
}

private SimpleDateFormat createDateFormat() {
    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    dateFormat.setLenient(false);
    return dateFormat;
}

}

0 个答案:

没有答案