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", "978030744@qq.com");
            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-ui
  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,如下图
  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.

    表示API操作中的单个参数

    @ApiImplicitParams

    A wrapper to allow a list of multiple ApiImplicitParam objects.

    允许多个apiImplicitParam对象列表的包装。

    @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.

    描述操作的可能响应。

    @ApiResponses

    A wrapper to allow a list of multiple ApiResponse objects.

    允许多个APIResponse对象列表的包装。

    @Authorization

    Declares an authorization scheme to be used on a resource or an operation.

    声明要在资源或操作上使用的授权方案。

    @AuthorizationScope

    Describes an OAuth2 authorization scope.

    描述OAuth2授权范围。

    @ResponseHeader

    Represents a header that can be provided as part of the response.

     表示可以作为响应的一部分提供的头。

     

  9. 需要注意:在resin容器中,swagger2不可启用,暂未找到原因!哪位好心人找到了,麻烦您告知!

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值