Swagger2之springMVC的简单集成

  1. 搭建一个springMVC的demo工程
  2. demo工程中pom.xml配置
                  <!-- 接口文档和UI -->
    		<dependency>
    			<groupId>io.springfox</groupId>
    			<artifactId>springfox-swagger2</artifactId>
    			<version>2.4.0</version>
    		</dependency>
    		<dependency>
    			<groupId>io.springfox</groupId>
    			<artifactId>springfox-swagger-ui</artifactId>
    			<version>2.4.0</version>
    		</dependency>
                    <!-- jackson必须加,否则swagger2异常  -->
                    <dependency>
    			<groupId>com.fasterxml.jackson.core</groupId>
    			<artifactId>jackson-core</artifactId>
    			<version>2.8.0</version>
    		</dependency>
    		<dependency>
    			<groupId>com.fasterxml.jackson.core</groupId>
    			<artifactId>jackson-databind</artifactId>
    			<version>2.6.3</version>
    		</dependency>
    		<dependency>
    		<groupId>com.fasterxml.jackson.core</groupId>
    		<artifactId>jackson-annotations</artifactId>
    		<version>2.6.3</version>
    		</dependency>
  3.   swagger2需要定义启动配置类SwaggerConfig.java
    package com.ppfuns.aaa.common;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    /**
     * Created with IntelliJ IDEA.
     * User: xxx
     * Date: 2019/1/16
     * Time: 10:31
     * To change this template use File | Settings | File Templates.
     */
    @Configuration  //启动配置
    @EnableSwagger2      //启动swagger
    @ComponentScan(basePackages = {"com.ppfuns.aaa.action"})  //扫描Action层接口列表目录
    @EnableWebMvc
    public class SwaggerConfig extends WebMvcConfigurationSupport {
        @Bean
        public Docket customDocket() {
            //
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo());
        }
    
        private ApiInfo apiInfo() {
            Contact contact = new Contact("22", "https://www.ppfuns.com", "[email protected]");
            return new ApiInfo("AAA 22",//大标题 title
                    "Swagger 22 demo",//小标题
                    "0.0.1",//版本
                    "www.baidu.com",//termsOfServiceUrl
                     contact,//作者
                    "22",//链接显示文字
                    "https://www.ppfuns1.com"//网站链接
            );
        }
    }
    
  4. 配置spring的xml配置,demo工程以springMvc为例,UI文件放在WEB-INF/swagger目录下
    <!--  swagger静态文件路径 -->
    	<mvc:resources mapping="/swagger/**" location="/WEB-INF/swagger/" cache-period="31556926"/>
    	<mvc:default-servlet-handler />
    	<bean class="com.ppfuns.aaa.common.SwaggerConfig" />

     

  5. 下载swagger-ui代码,引入dist目录下文件到WEB-INF/swagger/目录下;路径:https://github.com/swagger-api/swagger-uiSwagger2之springMVC的简单集成
  6. 修改其中的目录WEB-INF/swagger/index.html文件
    <!-- HTML for static distribution bundle build -->
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title>Swagger UI</title>
        <link rel="stylesheet" type="text/css" href="../../resources/swagger/swagger-ui.css" >
        <link rel="icon" type="image/png" href="../../resources/swagger/favicon-32x32.png" sizes="32x32" />
        <link rel="icon" type="image/png" href="../../resources/swagger/favicon-16x16.png" sizes="16x16" />
        <style>
          html
          {
            box-sizing: border-box;
            overflow: -moz-scrollbars-vertical;
            overflow-y: scroll;
          }
    
          *,
          *:before,
          *:after
          {
            box-sizing: inherit;
          }
    
          body
          {
            margin:0;
            background: #fafafa;
          }
        </style>
      </head>
    
      <body>
        <div id="swagger-ui"></div>
    
        <script src="/resources/swagger/swagger-ui-bundle.js"> </script>
        <script src="/resources/swagger/swagger-ui-standalone-preset.js"> </script>
        <script>
        window.onload = function() {
          // Begin Swagger UI call region
          const ui = SwaggerUIBundle({
    //        url: "https://petstore.swagger.io/v2/swagger.json",
         //url配置为:http://IP:PORT/{工程名}/v2/api-docs.json
            url:"http://localhost:8080/v2/api-docs.json",
            dom_id: '#swagger-ui',
            deepLinking: true,
            presets: [
              SwaggerUIBundle.presets.apis,
              SwaggerUIStandalonePreset
            ],
            plugins: [
              SwaggerUIBundle.plugins.DownloadUrl
            ],
            layout: "StandaloneLayout"
          })
          // End Swagger UI call region
    
          window.ui = ui
        }
      </script>
      </body>
    </html>
    
  7. 启动应用,访问http://localhost:8080/swagger/index.html,如下图Swagger2之springMVC的简单集成
  8. 以上swagger2和springMVC已集成在一起了,接下来对接口描述进行配置
    @Api(description = "日志")
    @Controller
    @RequestMapping("/log")
    public class LogController {
     
    	@Autowired
    	private ILogDAO mapper;
     
    	@ApiOperation(value = "查询记录(GET)", notes = "查询记录:http method is get", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    	@RequestMapping(value = "/user/queryByGet.json",method = RequestMethod.GET)
    	@ResponseBody
    	public APIResponse<List<Log>> queryByGet(
    			@ApiParam(required = true, hidden = false, value = "用户名") @PathVariable String name,
    			@ApiParam(required = true, hidden = false, value = "删除标识",example = "true",allowableValues = "true|false") @PathVariable boolean flag,
    			@ApiParam(required = true, value = "当前页",allowableValues = "1,100",example = "5") @RequestParam("currentPage") int currentPage,
    			@ApiParam(required = true, value = "每页显示数量") @RequestParam("pageSize") int pageSize) {
    		Page page = new Page();
    		page.setLow((currentPage - 1) * pageSize);
    		page.setHight(currentPage * pageSize);
    		page.setUsername(name);
    		List<Log> logs = mapper.selectUserLogByPage(page);
     
    		return APIResponse.returnSuccess(logs);
    	}
     
    	@ApiOperation(value = "查询记录(POST)", notes = "查询记录:http method is post", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    	@RequestMapping(value = "/user/queryByPost.json",method = RequestMethod.POST)
    	@ResponseBody
    	public APIResponse<List<Log>> queryByPost(
    			@ApiParam(required = true, hidden = false, value = "用户名") @PathVariable String name,
    			@ApiParam(required = true, hidden = false, value = "删除标识",example = "true",allowableValues = "true|false") @PathVariable boolean flag,
    			@ApiParam(required = true, value = "当前页",allowableValues = "1,5",example = "5") @RequestParam("currentPage") int currentPage,
    			@ApiParam(required = true, value = "每页显示数量") @RequestParam("pageSize") int pageSize) {
    		Page page = new Page();
    		page.setLow((currentPage - 1) * pageSize);
    		page.setHight(currentPage * pageSize);
    		page.setUsername(name);
    		List<Log> logs = mapper.selectUserLogByPage(page);
     
    		return APIResponse.returnSuccess(logs);
    	}
    }
    

    参数描述

    Controller参数注解详情
    名称 描述
    @Api

    Marks a class as a Swagger resource.

    标识一个类是swagger资源 

    @ApiImplicitParam  Represents a single parameter in an API Operation.
    @ApiImplicitParams A wrapper to allow a list of multiple ApiImplicitParam objects.
    @ApiModel

    Provides additional information about Swagger models.

    对模型(java类)进行说明,如http请求中接收参数

    @ApiModelProperty

    Adds and manipulates data of a model property.

    对模型(java类)中的字段进行说明

    @ApiOperation

    Describes an operation or typically a HTTP method against a specific path.

    描述一个http请求的操作:可指定httpMethod

    @ApiParam

    Adds additional meta-data for operation parameters.

    字段说明:表示对参数的添加元数据,可指定是否必传 

    @ApiResponse  Describes a possible response of an operation.
    @ApiResponse Describes a possible response of an operation.
    @ApiResponses A wrapper to allow a list of multiple ApiResponse objects.
    @Authorization

    Declares an authorization scheme to be used on a

    resource or an operation

    @AuthorizationScope Describes an OAuth2 authorization scope.
    @ResponseHeader Represents a header that can be provided as part of the response.

     

  9.  
  10.  
  11.