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

ddrv8njm  于 11个月前  发布在  Spring
关注(0)|答案(2)|浏览(99)

我试图在以下文档的帮助下,将自定义DateFormatter添加到我的spring/thymeleaf应用程序中:https://web.archive.org/web/20140606082846/http://www.thymeleaf.org/doc/html/Thymeleaf-Spring3.html#conversions-utility-object
问题是我没有使用xml configuration来定义bean,而是使用了一个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;
    }


但在这种情况下,我的应用程序中没有考虑格式化程序。
先谢谢你了,安东尼。

pcrecxhr

pcrecxhr1#

将其添加到WebMvcConfigurerAdapter

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

@Autowired
private DateFormatter dateFormatter;

@Bean
public DateFormatter dateFormatter() {
    return new DateFormatter("dd/MM/yyyy");
}

字符串

htrmnn0y

htrmnn0y2#

我使用了下面的配置类,并能够获得要调用的自定义格式化程序。我还没有能够获得要传入的messageSource,它总是空的,因为自动配置bean是在应用程序启动时稍后创建的。

@Configuration
public class ThymeleafConfig {
    @Autowired
    private MessageSource messageSource;

    @Bean
    public SpringSecurityDialect securityDialect() {
        return new SpringSecurityDialect();
    }

    @Bean
    public ConversionService conversionService() {
        DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService( false );
        conversionService.addFormatter( dateFormatter() );
        return conversionService;
    }

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

}

字符串
您还需要确保在模板中使用双括号括住字段。

<td th:text="${{user.createDate}}">12-MAR-2015</td>

相关问题