我对使用SpringBoot启动程序的SpringBoot的swagger文档有问题。
我在REST中使用了封装在java.time.Instant中的java.util.Optional,它工作得很好:
@GetMapping("/{subscriptionId}/{variableAlias}")
public PaginatedResultDTO<MonitoredVariableDTO> getReportedVariables(
@PathVariable String subscriptionId,
@PathVariable String variableAlias,
Optional<Instant> from,
Optional<Instant> to) { ... }但出于某种原因,Swagger文档无法正确处理可选类型,似乎通过反射作为EpochSeconds和Nano属性来处理它,而不是一个字段:

我希望能够像Spring那样以ISO格式从和到 instants,以及我如何在失眠中使用它:

当我试图移除可选包装时,它似乎起作用了。

是否有办法使这一工作与可选?谢谢你的建议!
Spring引导版本:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath />
</parent>Springfox启动版
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>发布于 2021-03-23 08:56:58
我们遇到的问题和你完全一样。我们通过这个SpringFox配置解决了这个问题:
@Configuration
@EnableSwagger2
public class SpringfoxConfiguration {
@Value("${api-doc.version}")
private String apiInfoVersion;
@Autowired
private TypeResolver typeResolver;
@Bean
public Docket customDocket(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("xxx")
//Some other code unrelated to this problem
.alternateTypeRules(
// Rule to correctly process Optional<Instant> variables
// and generate "type: string, format: date-time", as for Instant variables,
// instead of "$ref" : "#/definitions/Instant"
AlternateTypeRules.newRule(
typeResolver.resolve(Optional.class, Instant.class),
typeResolver.resolve(Date.class),
Ordered.HIGHEST_PRECEDENCE
))
.genericModelSubstitutes(Optional.class)
.select()
//Some more code unrelated to this problem
.build();
}
}发布于 2021-12-15 15:48:45
对于spring,问题在于它不使用自定义ObjectMapper,您已经将它定义为Bean。
Springfox使用new关键字创建自己的ObjectMapper。因此,您向自定义ObjectMapper注册的任何模块对于SpringFox来说都是毫无意义的。但是,Springfox提供了一个接口,可以用它自己的ObjectMapper注册模块。
在您的项目中创建一个配置bean,如下所示,它应该可以工作。
@Configuration
public class ObjectMapperModuleRegistrar implements JacksonModuleRegistrar {
@Override
public void maybeRegisterModule(ObjectMapper objectMapper) {
objectMapper.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.findAndRegisterModules();
}
}https://stackoverflow.com/questions/64876306
复制相似问题