gpt4 book ai didi

java - Swagger - Controller 未包含在 OpenApi 文档中

转载 作者:行者123 更新时间:2023-12-01 16:52:43 26 4
gpt4 key购买 nike

我有一个 JAX-RS Web 服务,我想使用 Swagger 2.1 对其进行记录。

配置是在我的 Servlet 中构建的:

public class FooWebservice extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
OpenAPI oas = new OpenAPI();
Info info = new Info()
.title("Foo-Webservice")
.version("1.0.0");

oas.info(info);

SwaggerConfiguration oasConfig = new SwaggerConfiguration()
.prettyPrint(true)
.openAPI(oas)
.resourcePackages(Stream.of("de.kembytes.foo.webservice.controller").collect(Collectors.toSet()));

try {
new JaxrsOpenApiContextBuilder()
.servletConfig(config)
.openApiConfiguration(oasConfig)
.buildContext(true);
} catch (OpenApiConfigurationException e) {
throw new ServletException(e.getMessage(), e);
}
}
}

此外,我还有一个定义操作的 Controller (在包 de.kembytes.foo.webservice.controller 中):

@Path("/foo")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Tag(name = "Foo")
public class FooController {
@POST
@Path("/calculate")
@Operation(summary = "returns bar",
responses = {
@ApiResponse(responseCode = "200", description = "bar", content = {
@Content(mediaType = MediaType.APPLICATION_XML, schema = @Schema(implementation = Bar.class)),
@Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = Bar.class)) }) })
public Bar calculate(@RequestBody(required = true, content = @Content(schema = @Schema(implementation = FooInput.class))) FooInput input) throws Exception {
Bar bar = new Bar();
bar.setValue1(...);
bar.setValue2(...);
bar.setValue3(...);

return bar;
}
}

当我启动我的应用程序并获取 OpenApi-Documentation 时,不包括 FooController 。它看起来像这样:

{
"openapi" : "3.0.1",
"info" : {
"title" : "Foo-Webservice",
"version" : "1.0.0"
}
}

配置在指定的资源包中,为什么FooController中没有加载配置?

最佳答案

我通过扫描我的包中是否有带有注释 @PathReflections library 的所有类解决了这个问题。 。然后我将它们全部设置为resourceClasses

init 方法现在看起来像这样:

@Override
public void init(ServletConfig config) throws ServletException {
OpenAPI oas = new OpenAPI();
Info info = new Info()
.title("Foo-Webservice")
.version("1.0.0");

oas.info(info);

Set<String> resourceClasses = new Reflections(getClass().getPackageName())
.getTypesAnnotatedWith(Path.class)
.stream().map(c -> c.getName())
.collect(Collectors.toSet());

SwaggerConfiguration oasConfig = new SwaggerConfiguration()
.prettyPrint(true)
.openAPI(oas)
.resourceClasses(resourceClasses);

try {
new JaxrsOpenApiContextBuilder()
.servletConfig(config)
.openApiConfiguration(oasConfig)
.buildContext(true);
} catch (OpenApiConfigurationException e) {
throw new ServletException(e.getMessage(), e);
}
}

关于java - Swagger - Controller 未包含在 OpenApi 文档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61658259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com