swagger-jaxrs 1.5.18
我在@ApplicationPath("/docs")上有一个应用程序,在它下面有一个位于@Path("/mydocs")的资源。因此,真正的端点是/api/docs/mydocs,但在swagger.json中生成的是/api/mydocs。
所需的swagger url: /api/docs/mydocs
实际的swagger url: /api/mydocs
要使其正常工作,必须在应用程序中使用@ApplicationPath("")
,在参考资料中使用@Path("/docs/mydocs")
,但我不想像这样随意更改所有路径以使其与Swagger一起工作。
@ApplicationPath( "/docs" )
@Api( tags = "docs" )
public class DocsConfig extends Application {
public DocsConfig() {
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion( "1.0" );
beanConfig.setSchemes( new String[]{ "http" } );
beanConfig.setHost( "localhost:8080" );
beanConfig.setBasePath( "/api" );
beanConfig.setResourcePackage( "com.my.company" );
beanConfig.setScan( true );
beanConfig.setTitle( "MY API" );
}
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new HashSet<>();
resources.add( io.swagger.jaxrs.listing.ApiListingResource.class );
resources.add( io.swagger.jaxrs.listing.SwaggerSerializers.class );
resources.add( DocsResource.class );
return resources;
}
}
@Stateless
@Path( "/mydocs" )
@Api( value = "mydocs" )
public class DocsResource {
@Context
ServletContext servletContext;
@Path( "/ui" )
@GET
public InputStream getFile() {
//some stuff
}
}
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jaxrs</artifactId>
<version>1.5.18</version>
</dependency>
发布于 2018-02-28 12:19:59
正如评论中提到的,仅在Swagger2.0中添加了对@ApplicationPath
的支持。在Swagger 1.5中,您可以选择将应用程序路径包含在swagger配置的基本路径中(如@imTachu所述):
final String applicationPath = DocsConfig.class.getAnnotation(ApplicationPath.class).value();
beanConfig.setBasePath("/api" + applicationPath);
这将导致生成的YAML如下所示:
...
basePath: "/api/docs"
...
paths:
/mydocs/ui:
...
或者,您可以编写一个ReaderListener
,根据需要修改生成的Swagger:
@SwaggerDefinition
public class SwaggerBasePathModifier implements ReaderListener {
@Override
public void beforeScan(Reader aReader, Swagger aSwagger) {
// do nothing
}
@Override
public void afterScan(Reader aReader, Swagger aSwagger) {
final Map<String, Path> newSwaggerPaths = new HashMap<>();
final String applicationPath = DocsConfig.class.getAnnotation(ApplicationPath.class).value();
for (final Map.Entry<String, Path> entry : aSwagger.getPaths().entrySet()) {
final currKey = entry.getKey().substring("/api".length(), entry.getKey().length())
final String newKey = "/api" + applicationPath + currKey;
newSwaggerPaths.put(newKey, entry.getValue());
}
aSwagger.setPaths(newSwaggerPaths);
}
}
这将导致生成的YAML中的每个路径都被修改。这就是你得到的:
...
basePath: "/api"
...
paths:
/docs/mydocs/ui:
...
通过使用第一个选项,所有请求都将使用相同的基本路径/api/docs
,而后一个选项允许您配置多个基本路径(例如,对于在同一应用程序中配置的多个JAX-RS服务器),并且更加灵活。
https://stackoverflow.com/questions/48913240
复制