package com.gy.subject.application.config;import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;import java.util.List;/*** mvc配置* @author 高悦* @version 1.0* @description: TODO* @date 2025/1/4 17:50*/
@Configuration
public class GlobalConfig extends WebMvcConfigurationSupport {@Overrideprotected void configureMessageConverters(List<HttpMessageConverter<?>> converters){super.configureMessageConverters(converters);converters.add(mappingJackson2HttpMessageConverter());}private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {ObjectMapper objectMapper = new ObjectMapper();objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);return new MappingJackson2HttpMessageConverter(objectMapper);}}
类定义
GlobalConfig
: - 包名:
com.gy.subject.application.config
,表示这个配置类属于项目的配置包. - 注解:
@Configuration
,表示这是一个Spring的配置类,Spring容器会在启动时加载并应用这个类中定义的配置. - 继承:
WebMvcConfigurationSupport
,这是一个Spring MVC的配置支持类,提供了许多用于自定义Spring MVC行为的方法,如配置消息转换器、视图解析器等.
方法
作用
- 自定义JSON序列化行为:通过配置
ObjectMapper
,你可以自定义Spring MVC中JSON的序列化行为,例如忽略空属性、处理空对象等. - 扩展Spring MVC配置:通过继承
WebMvcConfigurationSupport
并重写configureMessageConverters
方法,你可以扩展Spring MVC的默认配置,添加自定义的消息转换器,从而更好地满足项目的需求.
注意事项
- 版本兼容性:确保使用的Spring版本与代码兼容,特别是
WebMvcConfigurationSupport
类的使用. - 配置优先级:如果你使用了Spring Boot的自动配置,可能需要考虑配置的优先级,确保自定义配置能够正确应用.
- 其他配置:除了消息转换器,还可以根据需要配置其他Spring MVC的组件,如视图解析器、异常处理器等.