Springboot整合Swagger2.0、3.0

简介: Springboot整合Swagger2.0、3.0

概述

Swagger解决什么问题?

1、自动生成REST API 文档(替换了文档方式)

2、在线可调试后端接口(替换postman方式)

特点

  • 号称世界上最流行的API框架
  • Restful Api 文档在线自动生成器 => API 文档 与API 定义同步更新
  • 直接运行,在线测试API
  • 支持多种语言 (如:Java,PHP等)
  • 官网:https://swagger.io/

Swagger2.0

基本使用

加入依赖

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

要使用Swagger,我们需要编写一个配置类-SwaggerConfig来配置 Swagger

@Configuration //配置类
@EnableSwagger2// 开启Swagger2的自动配置
public class SwaggerConfig {  
}

编写HelloController,测试确保运行成功!

访问测试 :http://localhost:8080/swagger-ui.html ,可以看到swagger的界面

Swagger2 配置

Swagger2 的配置也是比较容易的,在项目创建成功之后,只需要开发者自己提供一个 Docket 的 Bean 即可,如下:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                //是否启用 正式环境改为false
                .enable(true)
                //基本信息配置
                .apiInfo(new ApiInfoBuilder()
                        .title("数字车间API文档")
                        .description("面朝大海 春暖花开")
                        .version("v1.0")
                        .license("apache 2.0")
                        .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.html")
                        .contact(new Contact("奥里给", "https://swagger.io/", "https://swagger.io/"))
                        .build())
                /*
                any() // 扫描所有,项目中的所有接口都会被扫描到
                none() // 不扫描接口
                通过方法上的注解扫描,如withMethodAnnotation(GetMapping.class)只扫描get请求
                withMethodAnnotation(final Class<? extends Annotation> annotation)
                通过类上的注解扫描,如.withClassAnnotation(Controller.class)只扫描有controller注解的类中的接口
                withClassAnnotation(final Class<? extends Annotation> annotation)
                basePackage(final String basePackage) // 根据包路径扫描接口
                * */
                .select()
                .apis(RequestHandlerSelectors.basePackage(" com.bim.yanchang.controller"))
                /*
                配置接口扫描过滤
                any() // 任何请求都扫描
                none() // 任何请求都不扫描
                regex(final String pathRegex) // 通过正则表达式控制
                ant(final String antPattern) // 通过ant()控制
                 */
                .paths(PathSelectors.ant("/user/**"))
                .build();
    }
}

如何动态配置当项目处于test、dev环境时显示swagger,处于prod时不显示?

如此,Swagger2 就算配置成功了,非常方便。

此时启动项目,输入 http://localhost:8080/swagger-ui.html,能够看到如下页面,说明已经配置成功了:

配置API分组

1、如果没有配置分组,默认是default。通过groupName()方法即可配置分组:

@Bean

public Docket docket(Environment environment) {

   return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())

       .groupName("hello") // 配置分组

       // 省略配置....

}

2、重启项目查看分组

3、如何配置多个分组?配置多个分组只需要配置多个docket即可:

@Bean
public Docket docket1(){
    return new Docket(DocumentationType.SWAGGER_2).groupName("group1");
}
@Bean
public Docket docket2(){
    return new Docket(DocumentationType.SWAGGER_2).groupName("group2");
}
@Bean
public Docket docket3(){
    return new Docket(DocumentationType.SWAGGER_2).groupName("group3");
}

4、重启项目查看即可

案例

方案1:
 
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestADXApi(Environment environment) {
        Profiles of = Profiles.of("dev","sit", "prd", "pre");
        boolean b = environment.acceptsProfiles(of);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(b)
                .groupName("a模块接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.a.controller"))
                .paths(PathSelectors.any())
                .build();
    }
 
    @Bean
    public Docket createRestSSPApi(Environment environment) {
        Profiles of = Profiles.of("dev","sit", "prd", "pre");
        boolean b = environment.acceptsProfiles(of);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(b)
                .groupName("b模块接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.b.controller"))
                .paths(PathSelectors.any())
                .build();
    }
 
    @Bean
    public Docket createRestADSApi(Environment environment) {
        Profiles of = Profiles.of("dev","sit", "prd", "pre");
        boolean b = environment.acceptsProfiles(of);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(b)
                .groupName("c模块接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.c.controller"))
                .paths(PathSelectors.any())
                .build();
    }
 
    @Bean
    public Docket createRestSystemApi(Environment environment) {
        Profiles of = Profiles.of("dev","sit", "prd", "pre");
        boolean b = environment.acceptsProfiles(of);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(b)
                .groupName("d模块接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.d.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    @Bean
    public Docket createRestFlowmApi(Environment environment) {
        Profiles of = Profiles.of("dev","sit", "prd", "pre");
        boolean b = environment.acceptsProfiles(of);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(b)
                .groupName("e模块接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.e.controller"))
                .paths(PathSelectors.any())
                .build();
    }
 
    @Bean
    public Docket createGameleyDmpApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("f模块接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.f.controller"))
                .paths(PathSelectors.any())
                .build();
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("管理后台接口")
                .description("管理后台接口")
                .version("1.0")
                .build();
    }
 
}
 
方案2:
@Configuration
@EnableSwagger2
@Profile({"dev","pre"})
public class SwaggerConfig {
    @Bean
    public Docket createGameleyDmpApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("a模块接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.a.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    @Bean
    public Docket createGameleyTopOnApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo2())
                .groupName("b模块接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.b.controller"))
                .paths(PathSelectors.any())
                .build();
    }
 
  
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("管理后台a模块接口")
                .description("管理后台接口")
                .version("1.0")
                .build();
    }
    private ApiInfo apiInfo2() {
        return new ApiInfoBuilder()
                .title("接口")
                .description("管理后台b模块接口")
                .version("1.0")
                .build();
    }
}
 

其他ui

1、默认的   访问 http://localhost:8080/swagger-ui.html

<dependency> 
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

2、bootstrap-ui  访问 http://localhost:8080/doc.html

<!-- 引入swagger-bootstrap-ui包 /doc.html-->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.1</version>
</dependency>

3、Layui-ui   访问 http://localhost:8080/docs.html

<!-- 引入swagger-ui-layer包 /docs.html-->
<dependency>
    <groupId>com.github.caspar-chen</groupId>
    <artifactId>swagger-ui-layer</artifactId>
    <version>1.1.3</version>
</dependency>

4、mg-ui   访问 http://localhost:8080/document.html

<!-- 引入swagger-ui-layer包 /document.html-->
<dependency>
    <groupId>com.zyplayer</groupId>
    <artifactId>swagger-mg-ui</artifactId>
    <version>1.0.6</version>
</dependency>


创建接口

接下来就是创建接口了

@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
public class UserController {
    @PostMapping("/")
    @ApiOperation("添加用户的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", defaultValue = "李四"),
            @ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "深圳", required = true)
    })
    public RespBean addUser(String username, @RequestParam(required = true) String address) {
        return new RespBean();
    }
    @GetMapping("/")
    @ApiOperation("根据id查询用户的接口")
    @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99", required = true)
    public User getUserById(@PathVariable Integer id) {
        User user = new User();
        user.setId(id);
        return user;
    }
    @PutMapping("/{id}")
    @ApiOperation("根据id更新用户的接口")
    public User updateUserById(@RequestBody User user) {
        return user;
    }
}

注解说明:

@Api 注解可以用来标记当前 Controller 的功能。

@ApiOperation 注解用来标记一个方法的作用。

@ApiImplicitParam 注解用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入。

如果有多个参数,则需要使用多个 @ApiImplicitParam 注解来描述,多个 @ApiImplicitParam 注解需要放在一个 @ApiImplicitParams 注解中。

需要注意的是,@ApiImplicitParam 注解中虽然可以指定参数是必填的,但是却不能代替 @RequestParam(required = true) ,前者的必填只是在 Swagger2 框架内必填,抛弃了 Swagger2 ,这个限制就没用了,所以假如开发者需要指定一个参数必填, @RequestParam(required = true) 注解还是不能省略。

如果参数是一个对象(例如上文的更新接口),对于参数的描述也可以放在实体类中。例如下面一段代码:

 

@ApiModel
public class User {
    @ApiModelProperty(value = "用户id")
    private Integer id;
    @ApiModelProperty(value = "用户名")
    private String username;
    @ApiModelProperty(value = "用户地址")
    private String address;
    //getter/setter
}

刷新刚刚打开的页面,可以看到如下效果:

可以看到,所有的接口这里都列出来了,包括接口请求方式,接口地址以及接口的名字等

二、Swagger3.0

依赖

这两个,一个用来生成接口文档(JSON 数据),另一个用来展示将 JSON 可视化。

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

在 3.0 版本中,我们不需要这么麻烦了,一个 starter 就可以搞定:

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

和 Spring Boot 中的其他 starter 一样,springfox-boot-starter 依赖可以实现零配置以及自动配置支持。也就是说,如果你没有其他特殊需求,加一个这个依赖就行了,接口文档就自动生成了。

支持 OpenAPI

什么是 OpenAPI?

OpenAPI 规范其实就是以前的 Swagger 规范,它是一种 REST API 的描述格式,通过既定的规范来描述文档接口,它是业界真正的 API 文档标准,可以通过 YAML 或者 JSON 来描述。它包括如下内容:

  • 接口(/users)和每个接口的操作(GET /users,POST /users)
  • 输入参数和响应内容
  • 认证方法
  • 一些必要的联系信息、license 等。

关于 OpenAPI 的更多内容,感兴趣的小伙伴可以在 GitHub 上查看:https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md

接口地址

3.0 中的接口地址也和之前有所不同,以前在 2.9.2 中我们主要访问两个地址:

现在在 3.0 中,这两个地址也发生了变化:

特别是文档页面地址,如果用了 3.0,而去访问之前的页面,会报 404。

注解

旧的注解还可以继续使用,不过在 3.0 中还提供了一些其他注解。

例如我们可以使用 @EnableOpenApi 代替以前旧版本中的 @EnableSwagger2。

但是实际使用中,@EnableOpenApi 注解的功能不明显,加不加都行。翻了下源码,@EnableOpenApi 注解主要功能是为了导入 OpenApiDocumentationConfiguration 配置类,如下:

1

2

3

4

5

6

@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)

@Target(value = {java.lang.annotation.ElementType.TYPE})

@Documented

@Import(OpenApiDocumentationConfiguration.class)

public @interface EnableOpenApi {

}

自动化配置类 OpenApiAutoConfiguration,如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

@Configuration

@EnableConfigurationProperties(SpringfoxConfigurationProperties.class)

@ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true", matchIfMissing = true)

@Import({

OpenApiDocumentationConfiguration.class,

SpringDataRestConfiguration.class,

BeanValidatorPluginsConfiguration.class,

Swagger2DocumentationConfiguration.class,

SwaggerUiWebFluxConfiguration.class,

SwaggerUiWebMvcConfiguration.class

})

@AutoConfigureAfter({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class,

HttpMessageConvertersAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class })

public class OpenApiAutoConfiguration {

}

显示详细信息

可以看到,自动化配置类里边也导入了 OpenApiDocumentationConfiguration。

所以在正常情况下,实际上不需要添加 @EnableOpenApi 注解。

根据 OpenApiAutoConfiguration 上的 @ConditionalOnProperty 条件注解中的定义,我们发现,如果在 application.properties 中设置 springfox.documentation.enabled=false,即关闭了 swagger 功能,此时自动化配置类就不执行了,这个时候可以通过 @EnableOpenApi 注解导入 OpenApiDocumentationConfiguration 配置类。技术上来说逻辑是这样,不过应用中暂未发现这样的需求(即在 application.properties 中关闭 swagger,再通过 @EnableOpenApi 注解开启)。

另外,以前我们用的 @ApiResponses/@ApiResponse 注解,在 3.0 中名字没变,但是所在的包变

另外,我们之前用的 @ApiOperation 注解在 3.0 中可以使用 @Operation 代替。

另外还有一些新注解如 @Parameter、Parameters、@Schema 等

参考地址:Swagger3.0,你所不知道的新变化! - 江南一点雨


相关文章
|
1月前
|
Java API Spring
【一】springboot整合swagger
【一】springboot整合swagger
44 0
|
1月前
|
XML Java 测试技术
【二】springboot整合自定义swagger
【二】springboot整合自定义swagger
34 0
|
1月前
|
Java Spring
Spring Boot3整合knife4j(swagger3)
Spring Boot3整合knife4j(swagger3)
594 1
|
1天前
|
前端开发 Java 程序员
Spring Boot (十五): 优雅的使用 API 文档工具 Swagger2
Spring Boot (十五): 优雅的使用 API 文档工具 Swagger2
|
28天前
|
API
1天搞定SpringBoot+Vue全栈开发 (2)RESTful API与Swagger
1天搞定SpringBoot+Vue全栈开发 (2)RESTful API与Swagger
|
1月前
|
Java Maven Spring
快速搭建spring boot 的 Swagger
快速搭建spring boot 的 Swagger
24 3
|
1月前
|
XML Java API
Spring Boot中使用集成swagger-bootstrap-ui
Spring Boot中使用集成swagger-bootstrap-ui
49 0
|
1月前
|
Java 应用服务中间件 网络安全
Nginx配置静态页面+springboot应用+swagger+SSL的实现
Nginx配置静态页面+springboot应用+swagger+SSL的实现
|
1月前
|
Java API Spring
Swagger使用-Spring Boot整合Swagger
Swagger使用-Spring Boot整合Swagger
55 0