Swagger中LocalDateTime默认格式固定,自定义注解配置无效
解决Swagger中LocalDateTime格式不生效的问题
问题根源
Swagger(尤其是Springfox版本)对Java 8的LocalDateTime类型有默认序列化规则,不会自动沿用Jackson的@JsonFormat配置;同时手动设置@ApiModelProperty的example会被Swagger自动生成的示例覆盖,导致配置无效。
解决方案
1. 确保依赖配置正确
首先确认引入Jackson处理JSR310时间类型的依赖,这是基础:
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency>
2. 针对Springfox(老版本Swagger)的配置
方法一:配置Docket使用Jackson的ObjectMapper
通过自定义ModelMapper让Swagger使用Jackson的序列化规则,这样@JsonFormat就能生效:
@Bean public Docket api(TypeResolver typeResolver) { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.your.package")) .paths(PathSelectors.any()) .build() .modelMapper(customModelMapper()); } private ModelMapper customModelMapper() { ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setObjectMapperConfigurer(context -> { ObjectMapper objectMapper = new ObjectMapper() .registerModule(new JavaTimeModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); // 替换为你的目标格式 context.setObjectMapper(objectMapper); return context; }); return modelMapper; }
方法二:自定义Swagger插件强制设置格式
实现ModelPropertyBuilderPlugin,手动覆盖LocalDateTime的格式和示例值:
@Component public class LocalDateTimeSwaggerConfig implements ModelPropertyBuilderPlugin { @Override public void apply(ModelPropertyContext context) { Optional<BeanPropertyDefinition> beanPropDef = context.getBeanPropertyDefinition(); if (beanPropDef.isPresent()) { Class<?> fieldType = beanPropDef.get().getField().getRawType(); if (LocalDateTime.class.equals(fieldType)) { context.getBuilder() .format("yyyy-MM-dd HH:mm:ss") // 自定义格式 .example("2016-01-01 09:10:50"); // 自定义示例 } } } @Override public boolean supports(DocumentationType documentationType) { return true; } }
3. 针对SpringDoc(新版本推荐)
如果使用Spring Boot 3.x,建议切换到SpringDoc OpenAPI(Springfox已停止维护),配置更简单:
- 引入SpringDoc依赖:
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.2.0</version> <!-- 适配Spring Boot 3.x --> </dependency>
- 在
application.yml中配置Jackson序列化规则:
springdoc: jackson: serialization: write-dates-as-timestamps: false
- 直接在POJO上使用
@Schema注解(替代@ApiModelProperty):
@Schema(required = true, example = "2016-01-01 09:10:50", pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime dateTime;
内容的提问来源于stack exchange,提问作者souvikc
相关产品推荐
相关产品推荐

