spring之使用自定义 DateFormatter 配置转换服务

cyq1162 阅读:128 2025-02-15 21:57:57 评论:0

在以下文档的帮助下,我正在尝试将自定义 DateFormatter 添加到我的 spring/thymeleaf 应用程序中: http://www.thymeleaf.org/doc/html/Thymeleaf-Spring3.html#conversions-utility-object

问题是我的 beans 定义没有使用 xml 配置,而是使用具有以下实现的 WebConfig.java 类:

@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = {"com.myapp.web.controller","net.atos.wfs.wts.adminportal.web.domain"}) 
public class WebConfig extends WebMvcConfigurerAdapter { 
 
private static final Logger LOG = LoggerFactory.getLogger(WebConfig.class); 
 
 
@Override 
public void addResourceHandlers(ResourceHandlerRegistry registry) { 
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); 
} 
 
@Override 
public void addInterceptors(InterceptorRegistry registry) { 
    LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); 
    localeChangeInterceptor.setParamName("lang"); 
    registry.addInterceptor(localeChangeInterceptor); 
} 
 
@Bean 
public LocaleResolver localeResolver() { 
    CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); 
    cookieLocaleResolver.setDefaultLocale(StringUtils.parseLocaleString("en")); 
    return cookieLocaleResolver; 
} 
 
@Bean 
public ServletContextTemplateResolver templateResolver() { 
    ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(); 
    resolver.setPrefix("/WEB-INF/views/"); 
    resolver.setSuffix(".html"); 
    //NB, selecting HTML5 as the template mode. 
    resolver.setTemplateMode("HTML5"); 
    resolver.setCacheable(false); 
    return resolver; 
 
} 
 
public SpringTemplateEngine templateEngine() { 
    SpringTemplateEngine engine = new SpringTemplateEngine(); 
    engine.setTemplateResolver(templateResolver()); 
    engine.setMessageResolver(messageResolver()); 
    engine.addDialect(new LayoutDialect()); 
    return engine; 
} 
 
@Bean 
public ViewResolver viewResolver() { 
 
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); 
    viewResolver.setTemplateEngine(templateEngine()); 
    viewResolver.setOrder(1); 
    viewResolver.setViewNames(new String[]{"*"}); 
    viewResolver.setCache(false); 
    return viewResolver; 
} 
 
@Bean 
public IMessageResolver messageResolver() { 
    SpringMessageResolver messageResolver = new SpringMessageResolver(); 
    messageResolver.setMessageSource(messageSource()); 
    return messageResolver; 
} 
 
@Override 
public void addFormatters(FormatterRegistry registry) { 
    super.addFormatters(registry); 
    registry.addFormatter(new DateFormatter()); 
} 
 
@Bean 
public MessageSource messageSource() { 
 
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 
    messageSource.setBasename("/WEB-INF/messages/messages"); 
    // if true, the key of the message will be displayed if the key is not 
    // found, instead of throwing a NoSuchMessageException 
    messageSource.setUseCodeAsDefaultMessage(true); 
    messageSource.setDefaultEncoding("UTF-8"); 
    // # -1 : never reload, 0 always reload 
    messageSource.setCacheSeconds(0); 
    return messageSource; 
} 
 
 } 

这是我的自定义 DateFormatter 的代码:

public class DateFormatter implements Formatter<Date> { 
 
    @Autowired 
    private MessageSource messageSource; 
 
 
    public DateFormatter() { 
        super(); 
    } 
 
    public Date parse(final String text, final Locale locale) throws ParseException { 
        final SimpleDateFormat dateFormat = createDateFormat(locale); 
        return dateFormat.parse(text); 
    } 
 
    public String print(final Date object, final Locale locale) { 
        final SimpleDateFormat dateFormat = createDateFormat(locale); 
        return dateFormat.format(object); 
    } 
 
    private SimpleDateFormat createDateFormat(final Locale locale) { 
 
        //The following line is not working (nullPointerException on messageSource) 
        //final String format = this.messageSource.getMessage("date.format", null, locale); 
        //The following line is working : 
        final String format = "dd/MM/yyyy"; 
        final SimpleDateFormat dateFormat = new SimpleDateFormat(format); 
        dateFormat.setLenient(false); 
        return dateFormat; 
    } 
 
} 

我的问题是:如何添加能够使用@Autowired 元素的自定义格式化程序?

xml配置是这样的:

<?xml version="1.0" encoding="UTF-8"?> 
<beans ...> 
 
  ...     
  <mvc:annotation-driven conversion-service="conversionService" /> 
  ... 
 
  <!-- **************************************************************** --> 
  <!--  CONVERSION SERVICE                                              --> 
  <!--  Standard Spring formatting-enabled implementation               --> 
  <!-- **************************************************************** --> 
  <bean id="conversionService" 
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 
    <property name="formatters"> 
      <set> 
        <bean class="thymeleafexamples.stsm.web.conversion.VarietyFormatter" /> 
        <bean class="thymeleafexamples.stsm.web.conversion.DateFormatter" /> 
      </set> 
    </property> 
  </bean> 
 
  ... 
 
</beans> 

我尝试在 WebConfig 类中使用以下配置:

@Bean 
    public FormattingConversionServiceFactoryBean conversionService() { 
        FormattingConversionServiceFactoryBean conversionService = new FormattingConversionServiceFactoryBean(); 
        Set<Formatter<?>> formatters = new TreeSet<Formatter<?>>(); 
        formatters.add(new DateFormatter()); 
        conversionService.setFormatters(formatters); 
        return conversionService; 
    } 

但在这种情况下,我的应用程序没有考虑格式化程序。

提前致谢, 安托万。

请您参考如下方法:

将此添加到您的 WebMvcConfigurerAdapter

@Override 
public void addFormatters(FormatterRegistry registry) { 
    registry.addFormatter(dateFormatter); 
} 
 
@Autowired 
private DateFormatter dateFormatter; 
 
@Bean 
public DateFormatter dateFormatter() { 
    return new DateFormatter("dd/MM/yyyy"); 
} 


标签:Spring
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号