Swagger(狂神说Java)(内含教学视频+源代码)

Posted FBI HackerHarry浩

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swagger(狂神说Java)(内含教学视频+源代码)相关的知识,希望对你有一定的参考价值。

Swagger(狂神说Java)(内含教学视频+源代码)

教学视频+源代码下载链接地址https://download.csdn.net/download/weixin_46411355/87415614

目录

一、学习目标:

  • 了解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 jar包

  • swagger2
  • ui

三、SpringBoot集成Swagger

3.1.新建一个SpringBoot的web项目




3.2.导入相关依赖


swagger2

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

swagger-ui

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

3.3编写一个Hello工程

package com.kuang.swagger.controller;

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

@RestController
public class HelloController 

    //  /    /error
    @RequestMapping(value = "/hello")
    public String hello()
        return "hello";
    



3.4 配置Swagger==>Config

package com.kuang.swagger.config;

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

@EnableSwagger2//开启Swagger2
@Configuration//等价于@Component
public class SwaggerConfig 




3.5.测试运行,访问http://localhost:8080/swagger-ui.html


swagger-ui.html来自于swagger-ui jar包下的resources目录下的swagger-ui.html

四、配置Swagger

Swagger的bean实例Docket
new Docket()源码
第一层源码:new Docket()构造方法


第二层源码:DocumentationType

代码写到如下

new Docket(DocumentationType.SWAGGER_2)
                .apiInfo()

.apiInfo的源码

第一层源码:
.apiInfo的源码

第二层源码:
ApiInfo的源码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package springfox.documentation.service;

import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ApiInfo 
    public static final Contact DEFAULT_CONTACT = new Contact("", "", "");
    public static final ApiInfo DEFAULT;
    private final String version;
    private final String title;
    private final String description;
    private final String termsOfServiceUrl;
    private final String license;
    private final String licenseUrl;
    private final Contact contact;
    private final List<VendorExtension> vendorExtensions;

    /** @deprecated */
    @Deprecated
    public ApiInfo(String title, String description, String version, String termsOfServiceUrl, String contactName, String license, String licenseUrl) 
        this(title, description, version, termsOfServiceUrl, new Contact(contactName, "", ""), license, licenseUrl, new ArrayList());
    

    public ApiInfo(String title, String description, String version, String termsOfServiceUrl, Contact contact, String license, String licenseUrl, Collection<VendorExtension> vendorExtensions) 
        this.title = title;
        this.description = description;
        this.version = version;
        this.termsOfServiceUrl = termsOfServiceUrl;
        this.contact = contact;
        this.license = license;
        this.licenseUrl = licenseUrl;
        this.vendorExtensions = Lists.newArrayList(vendorExtensions);
    

    public String getTitle() 
        return this.title;
    

    public String getDescription() 
        return this.description;
    

    public String getTermsOfServiceUrl() 
        return this.termsOfServiceUrl;
    

    public Contact getContact() 
        return this.contact;
    

    public String getLicense() 
        return this.license;
    

    public String getLicenseUrl() 
        return this.licenseUrl;
    

    public String getVersion() 
        return this.version;
    

    public List<VendorExtension> getVendorExtensions() 
        return this.vendorExtensions;
    

    static 
        DEFAULT = new ApiInfo("Api Documentation", "Api Documentation", "1.0", "urn:tos", DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList());
    


代码写到如下

再看第二层源码:ApiInfo的源码,代码可写到如下

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;

@EnableSwagger2//开启Swagger2
@Configuration//等价于@Component
public class SwaggerConfig 

    //作者信息
    Contact contact = new Contact("HHH","https://blog.kuangstudy.com/","3541434135@qq.com");


    //配置了Swagger的Docket的bean实例
    @Bean
    public Docket docket()
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    

    //配置Swagger信息:apiInfo
    private ApiInfo apiInfo()
        return new ApiInfo(
                "狂神的SwaggerAPI文档",
                "即使再小的帆也能远航",
                "v1.0",
                "https://blog.kuangstudy.com/",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    


重启启动类,浏览器访问:http://localhost:8080/swagger-ui.html

五、Swagger配置扫描接口

Docket.select()

提供一个Builder

Docket.apis()源码

需要传selector
所以传入RequestHandlerSelectors

package com.kuang.swagger.config;

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

@EnableSwagger2//开启Swagger2
@Configuration//等价于@Component
public class SwaggerConfig 

    //作者信息
    Contact contact = new Contact("HHH","https://blog.kuangstudy.com/","3541434135@qq.com");

    //配置了Swagger的Docket的bean实例
    @Bean
    public Docket docket()
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //RequestHandlerSelectors配置要扫描接口的方式
                //basePackage:指定扫描的包
                .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
                .build();//build 工厂模式

    
    //配置Swagger信息:apiInfo
    private ApiInfo apiInfo()
        return new ApiInfo(
                "狂神的SwaggerAPI文档",
                "即使再小的帆也能远航",
                "v1.0",
                "https://blog.kuangstudy.com/",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    


RequestHandlerSelectors源码如下

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package springfox.documentation.builders;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import java.lang.annotation.Annotation;
import org.springframework.util.ClassUtils;
import springfox.documentation.RequestHandler;

public class RequestHandlerSelectors 
    private RequestHandlerSelectors() 
        throw new UnsupportedOperationException();
    

    public static Predicate<RequestHandler> any() 
        return Predicates.alwaysTrue();
    

    public static Predicate<RequestHandler> none() 
        return Predicates.alwaysFalse();
    

    public static Predicate<RequestHandler> withMethodAnnotation(final Class<? extends Annotation> annotation) 
        return new Predicate<RequestHandler>() 
            public boolean apply(RequestHandler input) 
                return input.isAnnotatedWith(annotation);
            
        ;
    

    public static Predicate<RequestHandler> withClassAnnotation(final Class<? extends Annotation> annotation) 
        return new Predicate<RequestHandler>() 
            public boolean apply(RequestHandler input) 
                return (Boolean)RequestHandlerSelectors.declaringClass(input).transform(RequestHandlerSelectors.annotationPresent(annotation)).or(false);
            
        ;
    

    private static Function<Class<?>, Boolean> annotationPresent(final Class<? extends Annotation> annotation) 
        return new Function<Class<?>, Boolean>() 
            public Boolean apply(Class<?> input) 
                return input.isAnnotationPresent(annotation);
            
        ;
    

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) 
        return new Function<Class<?>, Boolean>() 
            public Boolean apply(Class<?> input) 
                return ClassUtils.getPackageName(input).startsWith(basePackage);
            
        ;
    

    public static Predicate<RequestHandler> basePackage(final String basePackage) 
        return new Predicate<RequestHandler>() 
            public boolean apply(RequestHandler input) 
                return (Boolean)RequestHandlerSelectors.declaringClass(input).transform(RequestHandlerSelectors.handlerPackage(basePackage)).or(true);
            
        ;
    

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) 
        return Optional.fromNullable(input.declaringClass());
    

RequestHandlerSelectors配置要扫描接口的方式

方法说明实例
basePackage指定扫描的包.basePackage(“com.kuang.swagger.controller”)
any扫描全部
none不扫描
withClassAnnotation(final Class<? extends Annotation> annotation)扫描类上的注解,参数是一个注解的反射对象.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
withMethodAnnotation(final Class<? extends Annotation> annotation)扫描方法上的注解.apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))

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.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;

@EnableSwagger2//开启Swagger2
@Configuration//等价于@Component
public class SwaggerConfig 

    //作者信息
    Contact contact = new Contact("HHH","https://blog.kuangstudy.com/","3541434135@qq.com");

    //配置了Swagger的Docket的bean实例
    @Bean
    public Docket docket()
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                /*
                * RequestHandlerSelectors配置要扫描接口的方式
                * 方法:
                *       basePackage:指定扫描的包
                *       any():扫描全部
                *       none():不扫描
                *       withClassAnnotation(final Class<? extends Annotation> annotation) 扫描类上的注解,参数是一个注解的反射对象
                *           示例:   .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                *       withMethodAnnotation(final Class<? extends Annotation> annotation) 扫描方法上的注解
                *           示例:    .apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))
                */
                .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
//                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
//                .apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))
                .build();//build 工厂模式

    
    //配置Swagger信息:apiInfo
    private ApiInfo apiInfo()
        return new ApiInfo(
                "狂神的SwaggerAPI文档",
                "即使再小的帆也能远航",
                "v1.0",
                "https://blog.kuangstudy.com/",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    


.paths()
//paths() 过滤什么路径
.paths(XXX)源代码

XXX需要传入一个PathSelector对象
PathSelectors.ant("/kuang/**")配置上这个就意味着扫描controller中方法的映射路径会多一层级,即扫描路径格式为:/kuang/XXX方法映射路径

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;

@EnableSwagger2//开启Swagger2
@Configuration//等价于@Component
public class SwaggerConfig 

    //作者信息
    Contact contact = new Contact("HHH","https://blog.kuangstudy.com/","3541434135@qq.com");

    //配置了Swagger的Docket的bean实例
    @Bean
    public Docket docket()
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                /*
                * RequestHandlerSelectors配置要扫描接口的方式
                * 方法:
                *       basePackage:指定扫描的包
                *       any():扫描全部
                *       none():不扫描
                *       withClassAnnotation(final Class<? extends Annotation> annotation) 扫描类上的注解,参数是一个注解的反射对象
                *           示例:   .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                *       withMethodAnnotation(final Class<? extends Annotation> annotation) 扫描方法上的注解
                *           示例:    .apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))
                */
                .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
//                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
//                .apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))
                //paths() 过滤什么路径
                .paths(PathSelectors.ant("/kuang/**"))
                .build();//build 工厂模式

    
    //配置Swagger信息:apiInfo
    private ApiInfo apiInfo()
        return new ApiInfo(
                "狂神的SwaggerAPI文档",
                "即使再小的帆也能远航",
                "v1.0",
                "https://blog.kuangstudy.com/",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());
    


在HelloController.java中加上一个@RequestMapping("/kuang")

再次重启,浏览器访问 http://localhost:8080/swagger-ui.html

enable是否启动Swagger,如果为False,则Swagger不能再浏览器中访问

再次重启,浏览器访问 http://localhost:8080/swagger-ui.html

问题:我只希望我的Swagger在生产环境中使用,在发布的时候不使用,应该怎么办?

解决思路:

  • 判断是不是生产环境 flag = false
  • 注入 enable(flag)

案例实操

application.properties

spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
spring.profiles.active=dev

application-dev.properties
application-pro.properties
application-test.properties

application-dev.properties

spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
server.port=8081

application-pro.properties

spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
server.port=8082

application-test.properties;

spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
server.port=8083

引入2个类Environment类和Profiles类

①Environment类

org.springframework.core.env.Environment
Environment类源码如下:

②Profiles类

org.springframework.core.env.Profiles
Profiles类
源码如下:

SwaggerConfig配置类.java

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 java.util.ArrayList;

@EnableSwagger2//开启Swagger2
@Configuration//等价于@Component
public class SwaggerConfig 

    //作者信息
    Contact contact = new Contact("HHH","https://blog.kuangstudy.com/","3541434135@qq.com");

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

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

        //获取项目的生产环境:
        //通过environment.accpetsProfiles判断是否处在自己设定的环境当中(dev 和 test)
        boolean flag = environment.acceptsProfiles(profiles);
        System.out.println("flag = " + flag)

B站狂神说Java笔记-Java入门学习

狂神视频地址

https://www.bilibili.com/video/BV12J41137hu


Java特性

  1. 简单性
  2. 面向对象
  3. 可移植性(跨平台)
  4. 高性能
  5. 分布式
  6. 动态性(反射)
  7. 多线程
  8. 安全性(安全)
  9. 健壮性

Java三大版本

  Java SE:标准版(桌面程序)
  Java ME:嵌入式开发(手机,小家电)
  Java EE:E企业级开发(web端,服务器开发)


JDK、JRE、JVM是什么?

  jdk:在jre之上扩充一些开发工具,让我们开发者使用的
  jre:运行时环境,只要安装了jre,就可以运行我们的java程序了。一般我们只需要下载安装jdk即可,因为jdk包含了jre。
  jvm:java虚拟机,把它当做一种规范,可以用软件来实现,也可以用硬件来实现。它就相当于在所有的操作系统上模拟了一个小小的cpu,去处理我们java相关的东西。java的跨平台核心是使用了java虚拟机,在不同的操作系统上安装jvm。

  Java是大小写敏感的语言


Java程序的运行机制

编译型
  把整个程序编译
解释型
  我说一句,你执行语句(网页 js,边解释,边执行)

各有利弊!
  Java属于以上两种类型型

  java先编译,再解释。

以上是关于Swagger(狂神说Java)(内含教学视频+源代码)的主要内容,如果未能解决你的问题,请参考以下文章

狂神说Java个人笔记-JavaWeb

狂神说Java --- 记录Spring学习笔记

遇见狂神说JAVA笔记 --- Mybatis 学习

B站狂神说Java笔记-java流程控制

B站狂神说Java笔记-Java入门学习

B站狂神说Java笔记-数组