swagget从创建项目开始

Swagger

学习目标:

  • 了解Swagger的作用和概念
  • 了解前后端分离
  • 在SpringBoot中集成Swagger

Swagger简介

前后端分离

Vue+SpringBoot

后端时代:前端只用管理静态页面;html==>后端。模板引擎JSP=>后端是主力

前后端分离时代:

  • 后端:后端控制层、服务层、数据访问层【后端团队】
  • 前端:前端控制层、视图层【前端团队】
    • 伪造后端数据,json。已经存在了,不需要后端,前端工程依旧能够跑起来
  • 前端后端如何交互?==>API
  • 前后端相互独立,松耦合;
  • 前后端甚至可以部署在不同的服务器上;

产生一个问题:

  • 前后端集成联调,前端人员和后端人员无法做到,即使协商,尽早解决“最终导致问题集中爆发”;
  • 首先指定schema[计划的提纲],实时更新最新的API,降低集成的风险;
  • 早些年:制定word计划文档;
  • 前后端分离:
    • 前端测试后端接口:postman
    • 后端提供接口,需要实时更新最新的消息及改动!

Swagger

  • 号称世界上最流行的API框架;
  • RestFul Api文档在线自动生成=>API文档与API定义同步更新
  • 直接运行,可以在线测试API接口;
  • 支持多种语言:(java、php)

官网:https://swagger.io/

在项目中使用Swagger需要springbox;

  • swagger2
  • ui

SpringBoot集成Swagger

  1. 新建springboot-web项目

    image-20211010151605123

    image-20211010151727765

    后面会添加 项目结构

    image-20211010223235027

  2. 导入相关依赖

    <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>3.0.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>3.0.0</version>
    </dependency>
    
    <!-- swagger3.0还要导入这个依赖 -->
    	 <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-boot-starter</artifactId>
                <version>3.0.0</version>
            </dependency>
    
    
  3. 编写一个helloword

  4. 配置Swagger==> Config

    //把第三方的swagger 添加到springboot中
    @Configuration
    @EnableSwagger2  //开启Swagger2
    public class SwaggerConfig {
    }
    
    
  5. 测试运行:http://localhost:8080/swagger-ui/index.html

    上面是3.0的 如果是2.9 访问地址是 http://localhost:8080/swagger-ui.html

    image-20211010155902242

配置Swagger

Swagger的bean实例 Docket;

package com.kuang.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;

//把第三方的swagger 添加到springboot中
@Configuration
@EnableSwagger2  //开启Swagger2
public class SwaggerConfig {
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }
    //配置Swagger信息=apiInfo
    private ApiInfo apiInfo(){
        Contact contact = new Contact("admin", "https://www.cnblogs.com/konglong/", "");
        return new ApiInfo(
                "Swagger demo",
                "即使再小的反也能远航",
                "v1.0",
                "https://www.cnblogs.com/konglong/",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    }
}

Swagger配置扫描接口

Docket.select()

package com.kuang.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
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;

//把第三方的swagger 添加到springboot中
@Configuration
@EnableSwagger2  //开启Swagger2
public class SwaggerConfig {
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //RequestHandlerSelectors,配置要扫描接口的方法
                //basePackage:指定要扫描的包
                //any():扫描全部
                //none():不扫描
                //withClassAnnotation():扫描类上的注解,参数是一个注解 withClassAnnotation(RestController.class)
                //withMethodAnnotation():扫描方法上的注解 withMethodAnnotation(GetMapping.class)
                .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
                //paths()过滤什么路径.paths(PathSelectors.ant("/kuang/**"))过滤掉kuang包下面的所有请求接口
                .paths(PathSelectors.ant("/kuang/**"))
                .build();
    }
    //配置Swagger信息=apiInfo
    private ApiInfo apiInfo(){
        //作者信息
        Contact contact = new Contact("admin", "https://www.cnblogs.com/konglong/", "");
        return new ApiInfo(
                "Swagger demo",
                "即使再小的反也能远航",
                "v1.0",
                "https://www.cnblogs.com/konglong/",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    }
}

改后

@Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //********、、、、、一套
                .select()
                //RequestHandlerSelectors,配置要扫描接口的方法
                //basePackage:指定要扫描的包
                //any():扫描全部
                //none():不扫描
                //withClassAnnotation():扫描类上的注解,参数是一个注解 withClassAnnotation(RestController.class)
                //withMethodAnnotation():扫描方法上的注解 withMethodAnnotation(GetMapping.class)
                .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
                //paths()过滤什么路径.paths(PathSelectors.ant("/kuang/**"))过滤掉kuang包下面的所有请求接口
//                .paths(PathSelectors.ant("/kuang/**"))
                .build()
                //*****到这里结束
                ;
    }

配置是否启动Swagger

@Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //enable 是否启动Swagger,如果为False,则Swagger不能在浏览器中访问
                .enable(false)
                //********、、、、、一套
                .select()
                //RequestHandlerSelectors,配置要扫描接口的方法
                //basePackage:指定要扫描的包
                //any():扫描全部
                //none():不扫描
                //withClassAnnotation():扫描类上的注解,参数是一个注解 withClassAnnotation(RestController.class)
                //withMethodAnnotation():扫描方法上的注解 withMethodAnnotation(GetMapping.class)
                .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
                //paths()过滤什么路径.paths(PathSelectors.ant("/kuang/**"))过滤掉kuang包下面的所有请求接口
//                .paths(PathSelectors.ant("/kuang/**"))
                .build()
                //*****到这里结束
                ;
    }

我们希望Swagger在生产环境中使用,在发布的时候不使用?

先搭建环境

  1. 在application.properties中写入spring.profiles.active=dev
  2. 新建application-dev.properties写入server.port=8081
  3. 新建application-pro.properties写入server.port=8082
  • 判断是不是生产环境 flag=false
  • 注入enable(flag)
 //配置了Swagger的Docket的bean实例
    @Bean
    public Docket docket(Environment environment){

        //设置要显示的Swagger环境
        Profiles profiles=Profiles.of("dev","test");

        //获取项目的环境:
        //通过environment.acceptsProfiles判断是否在自己设定的环境当中
        boolean flag = environment.acceptsProfiles(profiles);


        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(flag)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
                .build();
    }

重启项目 测试地址:http://localhost:8081/swagger-ui/index.html#/ 注意这时候端口号是8081

image-20211010174510183

如果application.properties中写入spring.profiles.active=pro时候 测试地址为

http://localhost:8082/swagger-ui/index.html#/ 注意这时候端口号是8082

spring.profiles.active=pro的测试结果为

image-20211010174530584

配置API文档的分组

如何配置多个分组?

package com.kuang.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
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 javax.print.Doc;
import java.util.ArrayList;

//把第三方的swagger 添加到springboot中
@Configuration
@EnableSwagger2  //开启Swagger2
public class SwaggerConfig {


    @Bean
    public Docket docket1(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("测试分组2");
    }
    @Bean
    public Docket docket2(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("测试分组3");
    }
    @Bean
    public Docket docket3(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("测试分组4");
    }




    //配置了Swagger的Docket的bean实例
    @Bean
    public Docket docket(Environment environment){

        //设置要显示的Swagger环境
        Profiles profiles=Profiles.of("dev","test");

        //获取项目的环境:
        //通过environment.acceptsProfiles判断是否在自己设定的环境当中
        boolean flag = environment.acceptsProfiles(profiles);


        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("测试分组1")
                .enable(flag)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
                .build();
    }



/**
//配置了Swagger的Docket的bean实例
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //enable 是否启动Swagger,如果为False,则Swagger不能在浏览器中访问
                .enable(false)
                //********、、、、、一套
                .select()
                //RequestHandlerSelectors,配置要扫描接口的方法
                //basePackage:指定要扫描的包
                //any():扫描全部
                //none():不扫描
                //withClassAnnotation():扫描类上的注解,参数是一个注解 withClassAnnotation(RestController.class)
                //withMethodAnnotation():扫描方法上的注解 withMethodAnnotation(GetMapping.class)
                .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
                //paths()过滤什么路径.paths(PathSelectors.ant("/kuang/**"))过滤掉kuang包下面的所有请求接口
//                .paths(PathSelectors.ant("/kuang/**"))
                .build()
                //*****到这里结束
                ;
    }
*/





    //配置Swagger信息=apiInfo
    private ApiInfo apiInfo(){
        //作者信息
        Contact contact = new Contact("admin", "https://www.cnblogs.com/konglong/", "");
        return new ApiInfo(
                "Swagger demo",
                "即使再小的反也能远航",
                "v1.0",
                "https://www.cnblogs.com/konglong/",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    }
}

结果:image-20211010212448336

配置实体类 常用注解

package com.kuang.swagger.pojp;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
//@Api(注释)
//给生成的实体中加上注释
@ApiModel("用户实体类")
public class User {

    //给生成的实体中加上注释
    @ApiModelProperty("用户名")
    public String username;
    @ApiModelProperty("密码")
    public String password;
}

image-20211010220245293

controller

package com.kuang.swagger.controller;

import com.kuang.swagger.pojp.User;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class HelloController {
    @GetMapping(value = "/hello")
    public String hello(){
        return "hello";
    }

    //只要我们的接口中,返回值中存在实体类,它就会被扫描到Swagger中
    @PostMapping(value = "/user")
    public User user(){
        return new User();
    }

    //Operation接口
    @ApiOperation("Hleoo控制器")
    @GetMapping(value = "hello2")
    public String hello2(@ApiParam("用户名") String username){
        return "hello"+username;
    }


    //Operation意思是接口
    @ApiOperation("post控制器")
    @GetMapping(value = "postt")
    public User postt(@ApiParam("用户名") User user){
        return user;
    }


}

image-20211010220425548

image-20211010220749723

总结:

  1. 可以通过Swagger给一些比较难理解的属性和接口,增加注释信息
  2. 接口文档实时更新
  3. 可以在线测试

【注意点】在正式发布的时候,关闭Swagger!!出于安全考虑,而且节省内存
学习视频 b站 狂神

posted @ 2021-10-10 22:27  小鲤鱼丿[小白]  阅读(71)  评论(0)    收藏  举报