SpringBoot引入Swagger3

Swagger3介绍

开发中有很多接口的开发,接口需要配合完整的接口文档才更方便沟通、使用,Swagger是一个用于自动生成在线接口文档的框架,并可在线测试接口,可以很好的跟Spring结合,只需要添加少量的代码和注解即可,而且在接口变动的同时,即可同步修改接口文档,不用再手动维护接口文档。Swagger3是17年推出的最新版本,相比于Swagger2配置更少,使用更方便

开发环境

JDK 11

SpringBoot 2.5.4


添加Maven依赖

<!--swagger3-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>


添加Swagger配置类


package com.springboot.admin.Swagger;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@EnableOpenApi
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                //设置通过什么方式定位需要自动生成文档的接口,这里定位方法上的@ApiOperation注解
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //接口URI路径设置,any是全路径,也可以通过PathSelectors.regex()正则匹配
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger3接口文档")
                .version("1.0")
                .description("API 描述")
                .build();

    }
}


使用Swagger

  1. 在接口类上添加@Api(tags = "操作接口"),tags的值是该类的作用,在文档页面会显示,value不会显示
  2. 在需要生成文档的接口上添加注解@ApiOperation
  3. 对请求参数添加@ApiParam

示例如下


package com.springboot.admin.controller;

import com.springboot.admin.jwt.JwtAuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;



@RestController
@Api(tags = "测试接口")
public class TestController {
    @Autowired
    JwtAuthService jwtAuthService;

    @GetMapping("/test")
    @ApiOperation(value="测试接口1", notes="获取当前目录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名字", dataType = "String", required = true),
            @ApiImplicitParam(name = "typeId", value = "类型ID", dataType = "Long", required = true)
    })
    public String test() throws Exception {

        // 获取当前目录
        ApplicationHome ah = new ApplicationHome(JwtAuthService.class);
        String docStorePath = ah.getSource().getParentFile().toString();
        System.out.println(docStorePath);

        return "hello world";
    }

    @GetMapping("/a")
    @Secured("ROLE_abc")
    @ApiOperation(value="测试接口2", notes="测试权限接口")
    public String a() {
        return "hello a api";
    }

    @GetMapping("/b")
    @PreAuthorize("hasRole('abcc')")
    @ApiOperation(value = "测试接口3",notes="测试权限接口333")
    public String b() {
        return "hello b api";
    }
}


查看效果:

启动服务后,就可以查看在线文档了,本地服务的地址是http://localhost:8080/swagger-ui/index.html,还可以通过Try it out 来测试。

如果应用有带上下文,那么地址地址也要加上上下文,比如:http://localhost:8091/bootService/swagger-ui/index.html


注意:

如果应用有引入security,那么需要将swagger相关资源放行:

// 放行swagger3相关资源

.antMatchers("/swagger-ui/**").permitAll()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/v3/**").permitAll()
.antMatchers("/swagger-resources/**").permitAll()


本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):