- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
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>
最佳答案
正如评论中提到的,仅在 Swagger 2.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 服务器)并且更加灵活。
关于java - 如何让Swagger使用@ApplicationPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48913240/
我是一名优秀的程序员,十分优秀!