Swagger-控制器未包含在OpenApi文档中



我有一个JAX-RSweb服务,我想用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);
}
}
}

此外,我还有一个控制器,它定义了操作(在包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文档时,FooController不包括在内。它看起来像这样:

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

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

我通过使用反射库扫描包中所有带有注释@Path的类,解决了这个问题。然后我将它们全部设置为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);
}
}

最新更新