如何在Spring Boot应用程序中手动配置Java8TimeDialect

时间:2017-05-20 09:10:03

标签: spring spring-boot thymeleaf

由于我仅将Thymeleaf用于电子邮件模板处理(不用于视图创建),因此我的应用程序类(即扩展SpringBootServletInitializer的类)中有以下排除项:

@SpringBootApplication(exclude=org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration.class)

缺少Spring Boot的自动配置,我需要手动配置Java8TimeDialect类,所以我已将以下bean添加到我的ThymeleafConfig类中:

@Bean
public Java8TimeDialect java8TimeDialect() {
    return new Java8TimeDialect();
}

尽管如此,我仍然遇到以下异常:

  

尝试调用方法   null上下文中的format(java.time.LocalDateTime,java.lang.String)   对象

显然,temporals对象未被添加到上下文中。我该如何解决这个问题?

我在我的POM文件中包含了Thymeleaf,如下所示:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
    <version>3.0.0.RELEASE</version>
</dependency>

1 个答案:

答案 0 :(得分:0)

添加pom.xml

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

然后:

package com.users.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;

import nz.net.ultraq.thymeleaf.LayoutDialect;

@Configuration
public class Thymeleaf {

    //TemplateEngine templateEngine = new TemplateEngine();

    @Bean
    public Java8TimeDialect java8TimeDialect() {
        return new Java8TimeDialect();
    }

    @Bean
    public LayoutDialect layoutDialect() {
        return new LayoutDialect();
   }

最后一次:

The time is: <strong th:text="${#temporals.format(now, 'dd/MMM/yyyy HH:mm')}">31/12/2015 15:00</strong>