java – 带有ResourceConfig的Swagger Core Jersey 2.X

我试图在我的应用程序中添加招摇.

我按照本指南https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5#using-a-custom-application-subclass

但我将Jersey配置为ResourceConfig,如下所示:

    @ApplicationPath("/resources/api")
     public class ApiApplication extends ResourceConfig {

    public ApiApplication() {
        super(MultiPartFeature.class);
        packages("my.rest.resources");
        register(io.swagger.jaxrs.listing.ApiListingResource.class);
        register(io.swagger.jaxrs.listing.SwaggerSerializers.class);

        BeanConfig beanConfig = new BeanConfig();
        beanConfig.setVersion("1.0.2");
        beanConfig.setSchemes(new String[]{"http"});
        beanConfig.setHost("localhost:8080");
        beanConfig.setBasePath("/resources/api");
        beanConfig.setResourcePackage("my.rest.resources");
        beanConfig.setScan(true);
    }
  }

它是否正确?

没有生成swagger.json.

根据我的理解,swagger文件应该在以下链接http://localhost/api/api-docs/swagger.json

更新:

将BasePath更改为resources / api

我在tomcat日志中也遇到以下异常:

    SEVERE: Servlet /XXXXXX threw load() exception
java.lang.NoSuchMethodError: org.reflections.util.ClasspathHelper.forPackage(Ljava/lang/String;[Ljava/lang/ClassLoader;)Ljava/util/Collection;
    at io.swagger.jaxrs.config.BeanConfig.classes(BeanConfig.java:189)
    at io.swagger.jaxrs.config.BeanConfig.setScan(BeanConfig.java:168)
    at my.rest.resources.apps.ApiApplication.<init>(ApiApplication.java:34)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)

最佳答案 >
ApiListingResource(swagger数据来自),只不过是另一个JAX-RS(Jersey)资源类.

@Path("/")
public class ApiListingResource {
    ...
    @GET
    ...
    @Path("/swagger.{type:json|yaml}")
    public Response getListing(..) {...}
    ...
}

因此资源路径将是@ApplicationPath(“/ resources / api”)和swagger资源路径/swagger.json.所以你需要访问/resources/api/swagger.json.
>您需要在BeanConfig中修复基本路径.此基本路径用于为swagger UI创建URL.使用基本路径“/ api”表示URL数据将导致UI访问不存在的/ api / yourresource.基本路径应该是servlet上下文(我猜你的情况是没有)和Jersey基本路径(/ resources / api)的组合.所以将BeanConfig基本路径设置为“/ resources / api”

点赞