Spring Boot 2.0整合Swagger2.8

Spring Boot 2.0整合Swagger2.8

Swagger简介

Swagger是一系列RESTful API 的工具, 通过Swagger可以获得项目的一种交互式文档, 客户端SDK的自动生成等功能. 从 Swagger Github 的官方主页摘录:

The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection.

软件版本

  • JDK1.8
  • spring boot 2.0
  • Swagger 2.8

[一]依赖引入

    <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>

【添加配置类】

package com.lx.soilparent.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author : Aslan
 * @version : v1.0
 * @time : 2018-07-24 14:57
 * @desc : Swagger2配置类
 */
@Configuration
@EnableSwagger2
public class Swagger2Config extends WebMvcConfigurationSupport {

    /**
     * 因为 Swagger2的资源文件都是在jar包里面,如果不在此处配置加载静态资源,
     * 会导致请求http://localhost:8081/swagger-ui.html失败
     *  <!--swagger资源配置-->
     *  <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
     *  <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
     *
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.lx.soilparent.controller"))
                .paths(PathSelectors.any())
                .build()
                //不需要时,或者生产环境可以在此处关闭
                .enable(true);

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("描述:测试使用Swagger2!")
                //服务条款网址
                .termsOfServiceUrl("www.aslan007.github.io")
                .contact("Aslan")
                .version("1.0")
                .build();
    }



}

[三]相关注解

@Api() 用于类的注解,标示该类的用途。
value会被tags覆盖,都是说明。

tags={"測試用controller","测试分组"}
这样写会有两个接口list
@Api(value = "测试各种方法",tags={"測試用controller"})
@RestController
public class TestWebController {
}

@ApiOperation() 用于方法;表示一个http请求的操作
value用于方法描述
notes用于提示内容
tags可以重新分组(视情况而用)
exam:

@ApiOperation(value = "测试Swagger2接口C",tags={"测试Swagger2接口分组B"},notes = "传入编号2,去数据库查询用户信息!")

@ApiParam() 用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
name–参数名
value–参数说明
required–是否必填

 public User getUserInfo(@ApiParam(name="id",value="用户id",required=true) Long id,@ApiParam(name="username",value="用户名") String username) {
//业务逻辑忽略
}

@ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述
都可省略
@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏

@ApiModel(value="user对象",description="用户对象user")
public class User implements Serializable{
    private static final long serialVersionUID = 1L;
     @ApiModelProperty(value="用户名",name="username",example="lx")
     private String username;
     @ApiModelProperty(value="状态",name="state",required=true)
      private Integer state;
      private String password;
      private String nickName;
      private Integer isDeleted;

      @ApiModelProperty(value="id数组",hidden=true)
      private String[] ids;
      private List<String> idList;

@ApiIgnore()用于类或者方法上,可以不被swagger显示在页面上

@ApiImplicitParam() 用于方法
表示单独的请求参数
@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
name–参数ming
value–参数说明
dataType–数据类型
paramType–参数类型
example–举例说明

   @ApiOperation(value = "测试Swagger2接口C",tags={"测试Swagger2接口分组B"},notes = "传入编号,去数据库查询用户信息!")
    @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long")
    @RequestMapping(value = "/swaTest3", method = RequestMethod.GET)
    public String TestSwa2(@PathVariable Long id){
        System.out.println("swaTest!");
        Optional<User> user = userRepository.findById(id);
        return  user.toString();
    }

【四】启动与应用

启动之后,访问:http://localhost:8080/swagger-ui.html,即可看到swagger的UI界面,且swagger具有调试功能;
这里写图片描述

【五】关于访问swagger-ui.html页面无法找到【404】问题的解决

在spring boot2.0中使用swagger,如果仅仅配置依赖,会出现swagger-ui.html无法访问的情况,一番查资料,发现是因为swagger-ui.html等资源文件都在依赖的jar包里面,需要将他的路径导入进来,在配置类里面加上如下内容即可:
这里写图片描述

网上有说,用配置类 extends WebMvcConfigurerAdapter,但是事实上,WebMvcConfigurerAdapter在spring boot 2.0 中已经过时了,不建议这样做,而且亲测使用这种方式依旧无法访问到swagger-ui.html。

【六】配置生产环境关闭swagger

作如下配置即可:
首先在yml配置文件里面配置好参数。
这里写图片描述
然后在配置类里面获取配置的参数。
这里写图片描述
最后在配置类里面配置启动或者关闭swagger。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_29534483/article/details/81199087