0%

在 SpringBoot2 中使用 LocalDatetime / LocalDate / LocalTime

一、引入

从JDK 8开始,引入了LocalDatetime类群,是增强版的Date。然,在SpringBoot中,并没有对这个东西内置支持,所以需要进行配置。

二、配置

主要是对Jackson进行配置。

Maven

1
2
3
4
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

注册

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import am.common.spring.BeanManager;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.yaml.snakeyaml.Yaml;

import java.time.format.DateTimeFormatter;

/**
* App Configuration
*
* @author kut
*/
@Configuration
@EnableJpaAuditing
public class AppConfiguration {

@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
String dateFormat = "yyyy-MM-dd";
String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";

return builder -> {
builder.simpleDateFormat(dateTimeFormat);
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
};
}
}

配置dozer

1
2
mapper = new DozerBeanMapper();
mapper.setMappingFiles(Collections.singletonList("dozerJdk8Converters.xml"));

配置完这个好,基本完成以下逻辑的配置:

1
2
entity -> vo -> jackson json
jackson json -> dto