Commit b0dbf454990198e3591b24925f8ed1945c01ddb7

Authored by 疯狂的狮子li
1 parent 33120e1d

update 优化 jackson 自动配置 改为使用 BeanPostProcessor 匿名处理

yudao-framework/yudao-spring-boot-starter-web/src/main/java/cn/iocoder/yudao/framework/jackson/config/YudaoJacksonAutoConfiguration.java
... ... @@ -5,31 +5,45 @@ import cn.iocoder.yudao.framework.jackson.core.databind.LocalDateTimeSerializer;
5 5 import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
6 6 import com.fasterxml.jackson.databind.ObjectMapper;
7 7 import com.fasterxml.jackson.databind.module.SimpleModule;
  8 +import lombok.extern.slf4j.Slf4j;
  9 +import org.springframework.beans.BeansException;
  10 +import org.springframework.beans.factory.config.BeanPostProcessor;
8 11 import org.springframework.context.annotation.Bean;
9 12 import org.springframework.context.annotation.Configuration;
10 13  
11 14 import java.time.LocalDateTime;
12 15  
  16 +@Slf4j
13 17 @Configuration
14 18 public class YudaoJacksonAutoConfiguration {
15 19  
16 20 @Bean
17   - @SuppressWarnings("InstantiationOfUtilityClass")
18   - public JsonUtils jsonUtils(ObjectMapper objectMapper) {
19   - SimpleModule simpleModule = new SimpleModule();
20   - /*
21   - * 1. 新增Long类型序列化规则,数值超过2^53-1,在JS会出现精度丢失问题,因此Long自动序列化为字符串类型
22   - * 2. 新增LocalDateTime序列化、反序列化规则
23   - */
24   - simpleModule
  21 + public BeanPostProcessor objectMapperBeanPostProcessor() {
  22 + return new BeanPostProcessor() {
  23 + @Override
  24 + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  25 + if (!(bean instanceof ObjectMapper)) {
  26 + return bean;
  27 + }
  28 + ObjectMapper objectMapper = (ObjectMapper) bean;
  29 + SimpleModule simpleModule = new SimpleModule();
  30 + /*
  31 + * 1. 新增Long类型序列化规则,数值超过2^53-1,在JS会出现精度丢失问题,因此Long自动序列化为字符串类型
  32 + * 2. 新增LocalDateTime序列化、反序列化规则
  33 + */
  34 + simpleModule
25 35 // .addSerializer(Long.class, ToStringSerializer.instance)
26 36 // .addSerializer(Long.TYPE, ToStringSerializer.instance)
27   - .addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE)
28   - .addDeserializer(LocalDateTime.class, LocalDateTimeDeserializer.INSTANCE);
  37 + .addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE)
  38 + .addDeserializer(LocalDateTime.class, LocalDateTimeDeserializer.INSTANCE);
29 39  
30   - objectMapper.registerModules(simpleModule);
  40 + objectMapper.registerModules(simpleModule);
31 41  
32   - JsonUtils.init(objectMapper);
33   - return new JsonUtils();
  42 + JsonUtils.init(objectMapper);
  43 + log.info("初始化 jackson 自动配置");
  44 + return bean;
  45 + }
  46 + };
34 47 }
  48 +
35 49 }
... ...