2015-02-24 64 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