我有一个要用JAX-RS
记录的Swagger 2.1
Web服务。
该配置是在我的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.tgallei.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.tgallei.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
中加载配置? 最佳答案
我已经通过用Reflections library注释@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);
}
}