2015-02-24 66 views
0

我想用日期格式化程序在用户前端显示格式化日期。当我创建格式化程序并注册fomatter时,自定义格式化程序不会在春天调用。 Follwing是我fomatter代码:Spring MVC:自定义DateFomratter不会被Spring调用

public class DateFormatter implements Formatter<Date>{ 

@Resource(name="messageSource") 
private MessageSource messageSource; 

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

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

private SimpleDateFormat createDateFormat(final Locale locale) { 
    final String format = this.messageSource.getMessage("app.dateformat", null, locale); 
    final SimpleDateFormat dateFormat = new SimpleDateFormat(format); 
    dateFormat.setLenient(false); 
    return dateFormat; 
}} 

以下是配置:

@Configuration 
@EnableWebMvc 
public class WebAppConfiguration extends WebMvcConfigurerAdapter{ 
-------------------------- 
@Override 
public void addFormatters(FormatterRegistry registry) { 
    registry.addFormatter(gatDateFormatter()); 
} 

@Bean(name="dateFormatter") 
public DateFormatter gatDateFormatter() { 
    return new DateFormatter(); 
}} 

回答

0
@Override 
public void addFormatters(FormatterRegistry registry) { 
    registry.addFormatter(dateFormatter); 
} 

@Autowired 
private DateFormatter dateFormatter; 

@Bean 
public DateFormatter dateFormatter() { 
    return new DateFormatter(); 
} 
+0

您可能要添加一些说明您的代码像它是如何解决这个问题,为什么 – Soma 2015-05-20 14:43:19

相关问题