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/","[email protected]");


    //配置了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/","[email protected]");

    //配置了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/","[email protected]");

    //配置了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/","[email protected]");

    //配置了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/","[email protected]");

    //配置了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);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(flag) //enable是否启动swagger,如果为false,则Swagger不能再浏览器中访问
                .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());
    }
}

此时application.properties为如下
在这里插入图片描述
启动启动类运行
在这里插入图片描述
flag = true
说明dev在Profiles里面,即在要显示的Swagger环境中
查看application-dev.properties
在这里插入图片描述

浏览器访问:http://localhost:8081/swagger-ui.html
在这里插入图片描述
将application.properties切换为pro生产环境
在这里插入图片描述

启动启动类运行
在这里插入图片描述
flag = false
说明pro不在Profiles里面,即在不在要显示的Swagger环境中
查看application-pro.properties
在这里插入图片描述
浏览器访问:http://localhost:8082/swagger-ui.html
.在这里插入图片描述
将application.properties切换为test测试环境
在这里插入图片描述
启动启动类运行
在这里插入图片描述

flag = true
说明test在Profiles里面,即在要显示的Swagger环境中
查看application-test.properties
在这里插入图片描述
浏览器访问:http://localhost:8083/swagger-ui.html
在这里插入图片描述

六、配置API文档的分组

application.properties先还原为dev开发环境
在这里插入图片描述

查看new Docket()的源码
在这里插入图片描述
所以需要手动配置groupName
在这里插入图片描述

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;

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

    //作者信息
    Contact contact = new Contact("HHH","https://blog.kuangstudy.com/","[email protected]");

    //配置了Swagger的Docket的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);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("狂神")
                .enable(flag) //enable是否启动swagger,如果为false,则Swagger不能再浏览器中访问
                .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());
    }
}

浏览器访问:http://localhost:8081/swagger-ui.html
在这里插入图片描述

问题:如何配置多个分组?

解答:配置多个Docket实例即可

在这里插入图片描述
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;

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

    
    public Docket docketByAndy(){
    
    
        return new Docket(DocumentationType.SWAGGER_2).groupName("Andy");
    }

    
    public Docket docketByBob(){
    
    
        return new Docket(DocumentationType.SWAGGER_2).groupName("Bob");
    }


    
    public Docket docketByHHH(){
    
    
        return new Docket(DocumentationType.SWAGGER_2).groupName("HHH");
    }


    //作者信息
    Contact contact = new Contact("HHH","https://blog.kuangstudy.com/","[email protected]");

    //配置了Swagger的Docket的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);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("狂神")
                .enable(flag) //enable是否启动swagger,如果为false,则Swagger不能再浏览器中访问
                .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());
    }
}

浏览器访问: http://localhost:8081/swagger-ui.html
在这里插入图片描述

七、实体类配置

0.导入lombok依赖

  <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>

1、新建一个实体类
com.kuang.swagger.pojo
User,java

package com.kuang.swagger.pojo;


import lombok.Data;


public class User {
    
    
    private String username;
    private String password;
}

只要我们的接口中,返回值中存在实体类,他就会被扫描到Swagger中

2.修改Controller层
在这里插入图片描述
HelloController.java

package com.kuang.swagger.controller;

import com.kuang.swagger.pojo.User;
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;


public class HelloController {
    
    

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

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

}

运行启动类,浏览器访问:http://localhost:8081/swagger-ui.html
在这里插入图片描述
@ApiModel(“XXX实体类”) 加在实体类上
@ApiModelProperty(“XXX成员变量”) 加在实体类的成员变量(属性)上
在这里插入图片描述

package com.kuang.swagger.pojo;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

("用户实体类")//给实体类加的一个文档注释

public class User {
    
    
    ("用户名")
    private String username;
    ("密码")
    private String password;
}

浏览器启动访问:http://localhost:8081/swagger-ui.html
在这里插入图片描述
Operation接口,不是放在类上的,是方法
@ApiOperation(“XXX方法”) 添加在XXXController的方法上
在这里插入图片描述
浏览器启动访问:http://localhost:8081/swagger-ui.html
在这里插入图片描述
@ApiParam(“方法的参数”)
在这里插入图片描述
浏览器启动访问:http://localhost:8081/swagger-ui.html
在这里插入图片描述

八、测试

1.测试hello方法

在这里插入图片描述
浏览器启动访问:http://localhost:8081/swagger-ui.html
找到HelloController的hello()方法
点击Try it out
在这里插入图片描述
点击Execute执行
在这里插入图片描述
在这里插入图片描述

2.测试user()方法

在这里插入图片描述
浏览器启动访问:http://localhost:8081/swagger-ui.html
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.测试hello2方法

测试hello2方法,先将hello2的@GetMapping改成@PostMapping,并给方法中的参数加入@RequestBody注解
修改之前
在这里插入图片描述
修改之后
在这里插入图片描述

测试
浏览器启动访问:http://localhost:8081/swagger-ui.html
在这里插入图片描述
在这里插入图片描述

4.测试hello3方法

在这里插入图片描述
浏览器启动访问:http://localhost:8081/swagger-ui.html
在这里插入图片描述
在这里插入图片描述

5.测试postt方法

5.1 直接传对象

在这里插入图片描述
浏览器启动访问:http://localhost:8081/swagger-ui.html
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

5.2 添加@RequestBody注解,则前端传一个JSON对象

在这里插入图片描述
浏览器启动访问:http://localhost:8081/swagger-ui.html
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

总结:

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

Swagger是一个优秀的工具,几乎所有大公司都有使用它
【注意点】在正式发布的时候,关闭Swagger!!!出于安全考虑,而且节省运行的内存。

猜你喜欢

转载自blog.csdn.net/weixin_46411355/article/details/128832499