代码之家  ›  专栏  ›  技术社区  ›  Dark Star1

是否可以从子路径而不是application上下文根为swagger根提供服务?

  •  1
  • Dark Star1  · 技术社区  · 6 年前

    我遵循这个例子 swagger configuration <jersey-context-root>/api-or-some-other-path 除了不管我把什么传给 config.setBasePath(some-sub-path); ersey应用程序上下文根 spring.jersey.application-path 基本路径 这是硬接线。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Paul Samsotha    6 年前

    看看你的链接和代码

    this.register(ApiListingResource.class);
    

    那个 ApiListingResource 是提供 swagger.json 终点。如果查看链接,可以看到该类使用路径( {type:json|yaml}

    @Path("/swagger.{type:json|yaml}")
    

    如果要更改路径,则需要以不同的方式进行注册。你需要做的是使用 Resource.builder(ResourceClass)

    Resource swaggerResource = Resource.builder(ApiListingResource.class)
            .path("foobar/swagger.{type:json|yaml}")
            .build();
    

    然后,而不是 ResourceConfig#register() 方法,则使用 ResourceConfig#registerResource(Resource)

    this.registerResource(swaggerResource);
    

    下面是一个完整的测试,使用 Jersey Test Framework

    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.Response;
    
    import org.glassfish.jersey.server.ResourceConfig;
    import org.glassfish.jersey.server.model.Resource;
    import org.glassfish.jersey.test.JerseyTest;
    import org.junit.Test;
    
    import static org.junit.Assert.assertEquals;
    
    public class ResourceBuilderTest extends JerseyTest {
    
        @Path("/swagger.{type:json|yaml}")
        public static class ApiListingResource {
    
            @GET
            @Produces("text/plain")
            public String get() {
                return "Hello World!";
            }
        }
    
        @Override
        public ResourceConfig configure() {
            Resource swaggerResource = Resource.builder(ApiListingResource.class)
                    .path("foobar/swagger.{type:json|yaml}")
                    .build();
            ResourceConfig config = new ResourceConfig();
            config.registerResources(swaggerResource);
            return config;
        }
    
        @Test
        public void testIt() {
            Response response = target("foobar/swagger.json")
                    .request()
                    .get();
    
            String data = response.readEntity(String.class);
            System.out.println(data);
            assertEquals("Hello World!", data);
        }
    }