java服务器使用swagger自动生成API文档

1.下载swaggerui,放入工程resource下

GitHub-swagger-ui

注意编辑index.html

      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
        url = window.location.toString();
        url = url.substring(0, url.lastIndexOf("/docs")) + "/test/swagger.json";
      }

2.编辑POM

    
        
        
            io.swagger
            swagger-jersey2-jaxrs
            1.5.3
        
    
    
        
            
                src/main/resources
                true
                
                    *.properties
                    *.xml
                
            
            
                src/main/resources/swaggerui
                true
                
                    **/*
                
                swaggerui/
            
        
    


3.编辑Main.java,添加两个函数。

    import io.swagger.jaxrs.config.BeanConfig;

    public static Server startServer() throws Exception {
        ...

        //swagger
        buildSwagger();
        handlerList.addHandler(buildSwaggerUI());

        ...
    }

    private static void buildSwagger() {
        // This configures Swagger
        BeanConfig beanConfig = new BeanConfig();
        beanConfig.setVersion("1.0.0");
        beanConfig.setResourcePackage("com.test.mavenproject.rest");
        beanConfig.setScan(true);
        beanConfig.setBasePath("/test");
        beanConfig.setDescription("Entity Browser API to demonstrate Swagger with Jersey2 in an "
                + "embedded Jetty instance, with no web.xml or Spring MVC.");
        beanConfig.setTitle("Entity Browser");
    }

    private static ContextHandler buildSwaggerUI() throws Exception {
        final ResourceHandler swaggerUIResourceHandler = new ResourceHandler();
        swaggerUIResourceHandler.setResourceBase(Main.class.getClassLoader().getResource("swaggerui").toURI().toString());
        final ContextHandler swaggerUIContext = new ContextHandler();
        swaggerUIContext.setContextPath("/docs");
        swaggerUIContext.setHandler(swaggerUIResourceHandler);
        return swaggerUIContext;
    }

4.编辑TestJerseyConfig.java

import io.swagger.jaxrs.listing.ApiListingResource;

//packages("com.test.mavenproject.rest");

改为

packages("com.test.mavenproject.rest", ApiListingResource.class.getPackage().getName());

5.编辑服务类

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


@Api("Session")
@Path("test1")
public class TestResource {
    @Inject
    public TestResource(
    ) {
        
    }
    
    @ApiOperation(
            value = "Get测试"
    )
    @GET
    @Path("get")
    @Produces(MediaType.TEXT_PLAIN)
    public String getTest(){
        return "called Get";
    }
}
更详细的Api介绍 All Classes(swagger-annotation)


完成后访问 http://服务器地址:端口/docs

你可能感兴趣的:(java服务器使用swagger自动生成API文档)