Spring Boot生成OpenAPI代码:路径与请求体日期格式不一致问题
Spring Boot生成服务端代码时路径参数与请求体日期格式不一致问题
配置Java 8日期库后,请求体中的日期通过Jackson以yyyy-MM-dd格式正常转换,但路径参数中的日期采用默认转换规则,要求格式为dd/MM/yyyy,给调用方带来极大困扰。
请求体日期配置
myDate: type: string format: date description: 'my date' example: '2018-02-05'
路径参数日期配置
- in: path name: my_date description: "my date" example: '2018-02-05' required: true schema: type: string format: date
路径参数日期处理调试情况
调试过程中发现,路径参数的日期转换默认采用dd/MM/yyyy格式,与请求体使用的yyyy-MM-dd格式不统一。
Maven插件配置
<configuration> <typeMappings> <typeMapping>Double=java.math.BigDecimal</typeMapping> </typeMappings> <apiPackage>package.api</apiPackage> <modelPackage>package.model</modelPackage> <invokerPackage>package.internal</invokerPackage> <inputSpec> ${basedir}/src/main/resources/spec/thespec.yaml </inputSpec> <language>spring</language> <withXml>true</withXml> <output>${project.build.directory}/generated-sources/swagger</output> <generateApiTests>true</generateApiTests> <ignoreFileOverride>${project.basedir}/.swagger-codegen-ignore</ignoreFileOverride> <configOptions> <sourceFolder>src/gen/java/main</sourceFolder> <dateLibrary>java8</dateLibrary> <withXml>true</withXml> <interfaceOnly>true</interfaceOnly> <!--swaggerDocketConfig>true</swaggerDocketConfig--> <serializableModel>true</serializableModel> <delegatePattern>true</delegatePattern> <bigDecimalAsString>true</bigDecimalAsString> <notNullJacksonAnnotation>true</notNullJacksonAnnotation> </configOptions> </configuration>
解决方法
1. 全局自定义日期转换器
路径参数的转换由Spring的Converter处理,而非Jackson。创建全局转换器统一解析格式:
import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import java.time.LocalDate; import java.time.format.DateTimeFormatter; @Component public class LocalDatePathConverter implements Converter<String, LocalDate> { private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); @Override public LocalDate convert(String source) { return LocalDate.parse(source, DATE_FORMAT); } }
2. 配置Swagger Codegen生成统一格式代码
在Maven插件的configOptions中添加日期格式参数,确保生成的接口方法自动使用指定格式:
<configOptions> <!-- 原有配置 --> <dateLibrary>java8</dateLibrary> <!-- 新增日期格式配置 --> <dateFormat>yyyy-MM-dd</dateFormat> <localDateDateFormat>yyyy-MM-dd</localDateDateFormat> </configOptions>
3. 接口方法单独指定格式
如果只需针对特定接口调整,可在生成的API方法上添加@DateTimeFormat注解:
import org.springframework.format.annotation.DateTimeFormat; import java.time.LocalDate; @GetMapping("/example/{my_date}") public ResponseEntity<?> getExample(@PathVariable("my_date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate myDate) { // 业务逻辑实现 }
内容的提问来源于stack exchange,提问作者Jigar Shah
相关产品推荐
相关产品推荐

