Springboot2x集成Swagger2

Springboot2x集成Swagger2

一、环境

  1. jdk 1.8
  2. Swagger 2.9.2
  3. Swagger-ui 2.9.2
  4. Spring Boot 2.1.9

二、代码示例

//导入依赖:
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
    <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger2</artifactId>
          <version>2.9.2</version>
      </dependency>

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
      <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger-ui</artifactId>
          <version>2.9.2</version>
        </dependency>

//添加如下配置类:

@Configuration
@EnableSwagger2
@EnableAutoConfiguration
public class Swagger2Config {

    /**
     *
     * @return
     */
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //此处根据情况自行添加需要将哪些接口纳入Swagger 文档管理。此处应用basePackage管理,还可以利用注解管理
                //如果填写错误的话会出现“No operations defined in spec!” 的问题。
                .apis(RequestHandlerSelectors.basePackage("com.iammn.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     *
     * @return
     */
    private ApiInfo apiInfo(){
        Contact contact = new Contact("Swagger2 demo", "http://localhost", "邮箱");
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTFUL API")
                .description("描述信息")
                .termsOfServiceUrl("http://localhost")
                .version("1.0")
                .contact(contact)
                .build();
    }
}

//示例controller 类:

@RestController
@Api(value = "测试 swagger2")
public class Swagger2TestController {

    /**
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/swagger", method = RequestMethod.GET)
    @ApiOperation(value = "返回用户输入的参数内容", notes = "notes")
    @ApiImplicitParam(paramType = "query", name = "param", value = "值",required = true, dataType = "string")
    public String swagger(String param){
        return param;
    }
}

然后直接访问:http://localhost:8080/swagger-ui.html (端口和ip根据自己的配置来)

三、Swagger常用注解:

swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息
@ApiImplicitParam:一个请求参数
@ApiImplicitParams:多个请求参数

四、常见错误

  1. 项目启动起来了,发现访问http://localhost:8080/swagger-ui.html 的时候,出现了404。最后找到原因是Swager-ui的依赖没有导入进来。没有提示报错,如果出现此情况,需要自己去核对依赖是否正确引入!
  2. 如果配置类中添加了注解 @EnableWebMvc。为了避免覆盖了,Spring Boot resources 下的静态资源。采用如下代码:
@Configuration
@EnableSwagger2
@EnableAutoConfiguration
@EnableWebMvc
public class Swagger2Config extends WebMvcConfigurationSupport {

  /**
   *
   * @return
   */
  @Bean
  public Docket createRestApi(){
      return new Docket(DocumentationType.SWAGGER_2)
              .apiInfo(apiInfo())
              .select()
              .apis(RequestHandlerSelectors.basePackage("com.iammn.controller"))
              .paths(PathSelectors.any())
              .build();
  }

  /**
   *
   * @return
   */
  private ApiInfo apiInfo(){
      Contact contact = new Contact("Swagger2 demo", "http://localhost", "邮箱");
      return new ApiInfoBuilder()
              .title("Spring Boot中使用Swagger2构建RESTFUL API")
              .description("描述信息")
              .termsOfServiceUrl("http://localhost")
              .version("1.0")
              .contact(contact)
              .build();
  }

  /**
   * 防止@EnableMvc把默认的静态资源路径覆盖了,手动设置的方式
   *
   * @param registry
   */
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
      // 解决静态资源无法访问
      registry.addResourceHandler("/**")
              .addResourceLocations("classpath:/static/");
      // 解决swagger无法访问
      registry.addResourceHandler("/swagger-ui.html")
              .addResourceLocations("classpath:/META-INF/resources/");
      // 解决swagger的js文件无法访问
      registry.addResourceHandler("/webjars/**")
              .addResourceLocations("classpath:/META-INF/resources/webjars/");
  }
}

5、环境配置:

如果说我需要在dev环境开启swagger2的调试,而在生产环境关闭swagger2的调试,可以使用如下配置:

swagger:
  enable: true

六、参考文档:

  1. https://blog.csdn.net/sanyaoxu_2/article/details/80555328
  2. 官网:http://swagger.io
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天技术总监说:小明,我们本次3.0改造,使用swagger2.0作为前后端分离的接口规范,它可以一键生成前后端的...
    coder小明阅读 8,665评论 4 12
  • spring security是spring家族的一个安全框架,入门简单。对比shiro,它自带登录页面,自动完成...
    b47251f96536阅读 3,043评论 0 1
  • NumPy - Ndarray 对象 NumPy 中定义的最重要的对象是称为 ndarray 的 N 维数组类型。...
    数据小黑升值记阅读 1,046评论 0 0
  • 图片加载框架Picasso源码的简单分析(一) 本篇文章只是对Picasso加载流程做加单的分析,相对于其他常用的...
    爱踢球的程序员阅读 4,021评论 0 50
  • 还有一周时间才能放五一假,家人和朋友们急不可耐地规划着四天时间。我想回娘家住两天,陪陪爸妈。 今天晚上儿子说他想出...
    李瑞居阅读 1,202评论 0 1