Springboot 2.6.7+swagger 3.0.0 集成使用

Springboot 2.6.7+swagger 3.0.0 集成使用,第1张

一、swagger背景介绍

两个技术主流时代:

  • 后端时代:前端只用管理静态页面-html,后端才是主力,模板引擎JSP=》这个时代后端人员工资远高于前端;
  • 前后端分离时代

①、后端:后端控制层、服务层、数据访问层【后端团队】

②、前端:前端控制层、视图层【前端团队】

--前端可以伪造JSON数据,数据已经存在,不需要后端,前端工程依然可以运行;

③、前后端如何交互:通过API

④、前后端分离优点:松耦合

⑤、前后端甚至可以部署在不同的服务器上;

⑥、产生的问题:前后端集成联调,前端人员和后端人员无法做到“尽早协商、尽早解决”,最终导致问题的爆发;

解决方案:首先制定schema【计划的提纲】,实时更新最新API,降低集成风险。

早些年:编写word文档;

前后端分离:

Ⅰ 、前端测试后端接口:postman

Ⅱ、后端提供接口,需要实时更新最新的消息及改动;

二、Swagger

  • 号称世界上最流行的api框架;
  • RestFul Api 文档在线文档自动生成工具=》api文档与api同步更新
  • 直接运行,可以轻松测试api接口
  • 支持多种语言:(java、PHP)
  • 官网:API Documentation & Design Tools for Teams | Swagger
  • 项目中使用swagger
    • 3.0以下的版本需要引入swagger2、swagger-UI
    • 3.0的版本需要引入springfox-boot-starter

三、SpringBoot集成Swagger

 本示例代码都上传到gitee上了,地址:https://gitee.com/huxiaofu/springboot-swagger2022.git

1、创建项目

 2、引入依赖


    io.springfox
    springfox-boot-starter
    3.0.0

PS:3.0.0以下的版本是引入swagger2和swagger-ui两个依赖

3、编写HelloWorld的Controller

package com.ligang.swagger.controller;

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

@RestController
public class HelloController {

    @RequestMapping(value = "/hello")
    public String hello(){
        return "Hello World!";
    }
}

4、配置swagger

package com.ligang.swagger.config;

import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2  //开启swagger
public class SwaggerConfig {
}

5、启动类增加注解

package com.ligang.swagger;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableOpenApi
@SpringBootApplication
public class SpringbootSwagger2022Application {

    public static void main(String[] args) {

        SpringApplication.run(SpringbootSwagger2022Application.class, args);
    }

}

6、application.yml配置文件

spring:
  mvc:
    pathmatch:
      matching-strategy: ANT_PATH_MATCHER

7、访问测试

http://localhost:8080/swagger-ui/index.html

PS:swagger3.0.0以下的版本访问地址是:http://localhost:8080/swagger-ui.html

四、配置Swagger

1、修改swagger首页中的swagger信息部分内容

package com.ligang.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

import java.util.ArrayList;

@Configuration
@EnableSwagger2  //开启swagger
public class SwaggerConfig {

    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo(){

        //作者信息
        Contact contact = new Contact(
                            "李刚",
                            "www.ligangTest.com",
                            "[email protected]");

        return new ApiInfo(
                "XX公司XX系统Swagger API文档",
                "梦想隔山海、山海皆可平!",
                "V1.0",
                "www.ligangTest.com",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>());
    }
}

 2、配置swagger扫描接口

        修改SwaggerConfig中的Docket docket()方法

@Bean
public Docket docket() {
    return new Docket(DocumentationType.OAS_30)
            .apiInfo(apiInfo())
            .select()
            //RequestHandlerSelectors.basePackage("com.ligang.swagger.controller") 指定需要扫描的包(一般使用这种方式)
            //RequestHandlerSelectors.any() 扫描全部
            //RequestHandlerSelectors.none() 不扫描
            //RequestHandlerSelectors.withClassAnnotation()
            //RequestHandlerSelectors.withMethodAnnotation()
            .apis(RequestHandlerSelectors.basePackage("com.ligang.swagger.controller"))
            //PathSelectors.ant("/swagger/**") 过滤某些路径(/swagger/**这些路径的接口不扫描)
            .build();
}

3、dev和test环境启动swagger,其他环境不启动swagger

application.yml

spring:
  mvc:
    pathmatch:
      matching-strategy: ANT_PATH_MATCHER
  profiles:
    active: dev
@Bean
public Docket docket(Environment environment) {
    //设置要显示swagger的环境,只有dev、test这两个环境才会显示swagger的api文档
    Profiles profiles = Profiles.of("dev","test");
    boolean isEnable = environment.acceptsProfiles(profiles);

    return new Docket(DocumentationType.OAS_30)
            .apiInfo(apiInfo())
            .enable(isEnable) //是否启动swagger,如果是false,则swagger不能在浏览器中访问
            .select()
            //RequestHandlerSelectors.basePackage("com.ligang.swagger.controller") 指定需要扫描的包(一般使用这种方式)
            //RequestHandlerSelectors.any() 扫描全部
            //RequestHandlerSelectors.none() 不扫描
            //RequestHandlerSelectors.withClassAnnotation()
            //RequestHandlerSelectors.withMethodAnnotation()
            .apis(RequestHandlerSelectors.basePackage("com.ligang.swagger.controller"))
            //PathSelectors.ant("/swagger/**") 过滤某些路径(/swagger/**这些路径的接口不扫描)
            .build();
}

浏览器测试,当profile的active设置为:pro时,浏览器访问

五、注解说明

1、@ApiOperation:用在方法上,给API增加方法说明。

@ApiOperation("hello方法")
@GetMapping(value = "/hello")
public String hello(){
    return "Hello World!";
}

2、@ApiImplicitParams 和 @ApiImplicitParam

        ①、@ApiImplicitParams: 用在方法上,包含一组参数说明。

        ②、@ApiImplicitParam:用来注解来给方法入参增加说明

@GetMapping(value = "/hello2")
@ApiImplicitParams({
    @ApiImplicitParam(name = "username",value = "用户名",paramType = "query",dataType = "String", required = false),
    @ApiImplicitParam(name = "password",value = "密码",paramType = "query",dataType = "String", required = false)
    })
public String hello2(String username,String password){

    return "Hello "+username +"," + password;
}

3、@ApiModel 和 @ApiModelProperty

        ①、@ApiModel:用在返回对象类上,描述一个Model的信息(一般用在请求参数无法使用 @ApiImplicitParam注解进行描述的时候)

        ②、@ApiModelProperty:描述一个model的属性

@ApiModel("用户对象")//给实体类增加文档注释
@AllArgsConstructor
@Data
@NoArgsConstructor
public class User {

    @ApiModelProperty("用户名")//给实体类字段增加文档注释
    private String username;

    @ApiModelProperty("密码")
    private String password;
}

其他不常用的注解,就不一一列举了。

六、测试api接口

 

 

总结:

  • 我们可以通过swagger给一些比较难理解的属性或者接口,增加注释说明信息;
  • 接口文档实时更新;
  • 可以在线测试;

Swagger是一个优秀的工具,几乎所有大公司都有使用它。

【注意】在正式发布的时候,关闭swagger!!出于安全考虑,而且节省内存。

本示例代码都上传到gitee上了,地址:https://gitee.com/huxiaofu/springboot-swagger2022.git

有什么疑问,欢迎交流。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/923819.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存