swagger 接口服务

Swagger 是一套接口文档规范通过这套规范,你只需要按照它的规范去定义接口及接口相关信息。再通过 Swagger 衍生出来的一系列项目和工具,就可以做到生成各种格式的接口文档,生成多做语言的客户端和服务端的代码,以及在线接口调试页面等等。这样,在开发新版本或者迭代版本的时候,只需要更新 Swagger 描述文件,就可以自动生成接口文档和客户端代码,做到调用端代码、服务端代码以及接口文档的一致性。

但即便如此,对于许多开发来说,编写这个 yml 或 json 格式的描述文件,本身也是有一定负担的工作,特别是在后面持续迭代开发的时候,往往会忽略更新这个描述文件,直接更改代码。久而久之,这个描述文件也和实际项目渐行渐远,基于该描述文件生成的接口文档也失去了参考意义。

所以作为 Java 界服务端的大一统框架 Spring,迅速将 Swagger 规范纳入自身的标准,建立了 Spring-swagger 项目,后面改成了现在的 Springfox。通过在项目中引入 Springfox,可以扫描相关的代码,生成该描述文件,进而生成与代码一致的接口文档和客户端代码。

下面是 swagger在 springboot中的使用介绍

1 依赖 pom

springfox 版本 常用 2.9.2,新版本 3.0.0

版本2.9.2

<!-- 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>

Swagger 新版本的依赖项只有一个,而旧版本的依赖项有两个,相比来说也简洁了很多。
新版本 3.0.0

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

2 配置

在 Spring Boot 的启动类或配置类中添加 @EnableSwagger2 注解 (新版本使用 @EnableOpenApi ),开启 Swagger。

访问地址:

http://项目实际地址/swagger-ui.html
新版本则是:http://项目实际地址/swagger-ui/index.htmlhttp://项目实际地址/swagger-ui/

@Configuration
@EnableSwagger2     // v2.* 使用该注解
//@EnableOpenApi   // v3.0.0 使用该注解
public class SwaggerConfig {
    
    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     * 
     * @return
     */
    @Bean
    public Docket createRestApi() {
     
         List<Parameter> pars = new ArrayList<Parameter>();
        pars.add(new ParameterBuilder().name("token").description("token").modelRef(new ModelRef("String")).parameterType("header").required(false).build());  // 添加请求头参数

        return new Docket(DocumentationType.SWAGGER_2)  //文档类型  v3.0.0 用 DocumentationType.OAS_30
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.swaggerTest.controller"))  // 设置扫描包位置。默认和springboot 的 @ComponentScan 中的包 一致
                .paths(PathSelectors.any())  // 设置匹配路径,可设置 所扫描包里的哪些接口对外暴露
                .build()
                .globalOperationParameters(pars);
    }
    
    /**
     * 创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://项目实际地址/swagger-ui.html
     * 访问地址(新版本):http://项目实际地址/swagger-ui/index.html 、 http://项目实际地址/swagger-ui/
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("更多请关注http://www.baidu.com")
                .termsOfServiceUrl("http://www.baidu.com")
                .contact("sunf")
                .version("1.0")
                .build();
    }
}

v3.0.0 和 之前的 v2.x 差异在于:
1)引用依赖不同,
2)开启注解不同(@EnableSwagger2 ,@EnableOpenApi ),
3)使用文档类型不同(DocumentationType.SWAGGER_2,DocumentationType.OAS_30 ) ,
4)界面UI 有差异

3 详细说明注解

经过之上的配置,其实就可以 在 UI页面上访问,并调试 接口了,只是一些接口说明都是默认的。
可以添加一些注解,增加接口说明信息。

@RequestMapping("/user")
@Api(tags = "用户服务相关接口描叙")
public class HelloController {

        @GetMapping("/findAll")
        @ApiOperation(value = "查询所有用户接口",
                notes = "<span style='color:red;'>描叙:</span>&nbsp;&nbsp;用来查询所有用户信息的接口")
       @ApiImplicitParams({
                @ApiImplicitParam(name = "id", value = "用户 id", dataType = "String", defaultValue = "21"),
                @ApiImplicitParam(name = "name", value = "用户姓名", dataType = "String", defaultValue = "白衣")
        })
        public Map<String, Object> save(String id, String name) {
            System.out.println("id = " + id);
            System.out.println("name = " + name);
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("name", name);
            return map;
        }

        @PostMapping("save2")
        public Map<String, Object> save2(@RequestBody User user) {
            System.out.println("id = " + user.getId());
            System.out.println("name = " + user.getName());
            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("name", user.getName());
            return map;
        }


}


// User 类

@Data
@ApiModel(description= "接口数据模型说明")
public class User {

    @ApiModelProperty(value = "用户id",example = "35")   // 参数说明
    private String id;

    @ApiModelProperty(value = "姓名",example = "张三")
    private String name;
}

https://blog.csdn.net/unique_perfect/article/details/109224151
https://www.zhihu.com/question/63803795/answer/1780508067

Swagger官网 :http://swagger.io/
springfox:http://springfox.github.io/springfox/docs/current/#getting-started

posted @ 2021-06-24 17:58  zhanglw  阅读(416)  评论(0编辑  收藏  举报