JHipster下OpenAPI生成代码的使用方法及参数转换错误排查
解决方案
一、OpenAPI生成代码的正确使用方式
JHipster集成的OpenAPI Generator插件默认将生成的代码输出到build/generated/sources/openapi目录,Gradle已经自动将该目录注册为项目的编译源目录,无需手动拷贝生成代码到src目录,避免代码冗余和版本管理问题。
你只需要确保两个配置即可正常使用:
- 确认
build.gradle中openApiGenerate任务的interfaceOnly属性设置为true,该配置会仅生成接口、DTO、Delegate类,不会生成冗余的Controller代码 - 你已经实现的
ProductApiDelegateImpl加了@Service注解,Spring会自动将该实现类注入到生成的Controller层,自动暴露对应API接口
如果需要自定义生成代码的输出路径,可修改openApiGenerate任务的outputDir属性到指定目录,不过不推荐该做法,生成代码无需提交到版本库,每次构建自动生成即可。
二、枚举参数转换400错误修复
错误原因:你加的@JsonCreator注解仅对JSON格式的请求体生效,Query参数的转换走Spring自带的Converter逻辑,默认会调用Enum.valueOf()方法匹配枚举常量名(大写的AVAILABLE),你传入的小写available无法匹配,因此报错。
可选择以下任意一种方案修复:
方案1:注册全局转换器
新增转换器类,SpringBoot会自动扫描注册到全局转换服务:
import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; @Component public class ProductStatusConverter implements Converter<String, ProductStatus> { @Override public ProductStatus convert(String source) { return ProductStatus.fromValue(source); } }
方案2:枚举类直接实现Converter接口
修改现有ProductStatus枚举,增加Converter实现:
import org.springframework.core.convert.converter.Converter; import javax.persistence.Converter; @Converter(autoApply = true) public enum ProductStatus implements Converter<String, ProductStatus> { AVAILABLE("available"), UNAVAILABLE("unavailable"); private String value; ProductStatus(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static ProductStatus fromValue(String value) { for (ProductStatus b : ProductStatus.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } @Override public ProductStatus convert(String source) { return fromValue(source); } }
三、实现类代码修正
你现有ProductApiDelegateImpl中存在逻辑错误,ProductStatus.valueOf()仅支持传入枚举常量名(大写),需要改为调用你已经实现的fromValue方法:
// 错误写法 .map(statusValue -> new Product().id(RandomUtils.nextLong()).status(ProductStatus.valueOf(statusValue))) // 修正后写法 .map(statusValue -> new Product().id(RandomUtils.nextLong()).status(ProductStatus.fromValue(statusValue)))
内容的提问来源于stack exchange,提问作者dungreact
相关产品推荐
相关产品推荐

