Springboot整合Swagger-plus

目录

搭建项目

编写swagger配置文件

swagger常用注解

使用示例

Swagger皮肤 - knife4j

生成md接口文档

参考网站


之前写的swagger1.0版的ui确实一般(很丑),所以改版了:使用了加强版swagger + 皮肤

搭建项目

我的环境:

Idea

创建spring项目,勾选web:

导入Swagger依赖:

<dependency>
    <groupId>cn.weiguangfu</groupId>
    <artifactId>springfox-swagger2-plus</artifactId>
    <version>2.7.0-1</version>
</dependency>

编写swagger配置文件

下面的basePackage改为你对应的项目包级。

import cn.weiguangfu.swagger2.plus.annotation.EnableSwagger2Plus;
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 java.util.ArrayList;

// swagger配置类
@Configuration
@EnableSwagger2Plus
public class Swagger2Config
{
    @Bean
    public Docket docket()
    {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfo(
                        "接口文档",       					 // swagger页面标题
                        "该文档描述了**项目接口信息",   	// swagger页面描述
                        "1.1",          					// 标题右边的版本号
                        "",      							// 留空
                        new Contact("", "", ""),   			// 作者联系方式
                        "",									// license
                        "",									// license的url
                        new ArrayList()))
                .groupName("group1")  // 分组名称
                // 指定扫描接口的包,select和build成组出现
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.helloSwagger"))
                .build();
    }
    
}

 在application.yml中加入swagger增强语句

swagger:
  plus:
    enable: true

因为我用的springboot2.6.6,直接启动项目会有bug:

 Failed to start bean 'documentationPluginsBootstrapper'

查找资料发现是版本问题,只需要在配置文件下加入即可解决。

 spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

bug详细原因参见这位大哥的文章:

SpringBoot更新到2.6.0启动报错 Failed to start bean ‘documentationPluginsBootstrapper‘ 问题处理_CHQIUU的博客-CSDN博客

swagger常用注解

1、@Api():用在请求的类上,表示对类的说明,也代表了这个类是swagger2的资源

参数:

 tags:说明该类的作用,参数是个数组,可以填多个。
 value="该参数没什么意义,在UI界面上不显示,所以不用配置"
 description = "用户基本信息操作"

2、@ApiOperation():用于方法,表示一个http请求访问该方法的操作

参数:

 value="方法的用途和作用"    
 notes="方法的注意事项和备注"    
 tags:说明该方法的作用,参数是个数组,可以填多个。
 格式:tags={"作用1","作用2"} 
 (在这里建议不使用这个参数,会使界面看上去有点乱,前两个常用)

3、@ApiModel():用于响应实体类上,用于说明实体作用

参数:

 description="描述实体的作用"  

4、@ApiModelProperty:用在属性上,描述实体类的属性

参数:

 value="用户名"  描述参数的意义
 name="name"    参数的变量名
 required=true     参数是否必选

5、@ApiImplicitParams:用在请求的方法上,包含多@ApiImplicitParam

6、@ApiImplicitParam:用于方法,表示单独的请求参数

参数:

 name="参数ming" 
 value="参数说明" 
 dataType="数据类型" 
 paramType="query" 表示参数放在哪里
     · header 请求参数的获取:@RequestHeader
     · query   请求参数的获取:@RequestParam
     · path(用于restful接口) 请求参数的获取:@PathVariable
     · body(不常用)
     · form(不常用) 
 defaultValue="参数的默认值"
 required="true" 表示参数是否必须传

7、@ApiParam():用于方法,参数,字段说明 表示对参数的要求和说明

参数:

 name="参数名称"
 value="参数的简要说明"
 defaultValue="参数默认值"
 required="true" 表示属性是否必填,默认为false

8、@ApiResponses:用于请求的方法上,根据响应码表示不同响应,一个@ApiResponses包含多个@ApiResponse

9、@ApiResponse:用在请求的方法上,表示不同的响应

参数

 code="404"    表示响应码(int型),可自定义
 message="状态码对应的响应信息"  

10、@ApiIgnore():用于类或者方法上,不被显示在页面上

11、@Profile({"dev", "test"}):用于配置类上,表示只对开发和测试环境有用

使用示例

controller:

 @Api("获取用户信息")
 @RestController
 public class PersonController {
 ​
     @PostMapping("/list")
     @ApiOperation(value = "分页显示Person数据",notes = "")
     public R getPersonPage(@ApiParam(name = "每页数据量",example = "5")@RequestBody int number,
                            @ApiParam(name = "页码",value = "当前页码",example = "1")@RequestBody int page){
         List<Person> personList = new ArrayList<>();
         return R.ok(personList);
     }
 }

entity:

 @Data
 @AllArgsConstructor
 @NoArgsConstructor
 @ApiModel("用户实体类")
 public class Person {
 ​
     @ApiModelProperty(value = "用户名" , example = "张三")
     private String name ;
 ​
     @ApiModelProperty(value = "年龄" , example = "19")
     private Integer age ;
 ​
     @ApiModelProperty(value = "手机号码" , notes = "11位手机号码")
     private String phone ;
 ​
 }

result:

 @ApiModel(value = "统一返回结果")
 @Data
 public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;
 ​
    @ApiModelProperty(value = "响应码",position = 1,example = "200") // position属性显式地在参数中的顺序
    Integer code;
 ​
    @ApiModelProperty(value = "消息",position = 2,example = "操作成功")
    String message;
 ​
    @ApiModelProperty(value = "操作是否成功",position = 3,example = "true")
    Boolean success;
 ​
    @ApiModelProperty(value = "相应参数",position = 4)
    T data;
 ​
    public R() {
       this.code = 0;
       this.message = "success";
       this.success = true;
    }
 ​
    public R(T data){
       this();
       setData(data);
    }
 ​
    public static <T> R<T> ok(T data){
       return new R<T>(data);
    }
 ​
 }

启动项目,打开网址:http://localhost:8080/swagger-ui.html ,即可看见接口。

swagger页面操作简单,可以轻松查看接口参数(当然要代码里写的详细啊),也可以轻松发送请求测试接口,具体使用操作操作不多描述。

Swagger皮肤 - knife4j

如果觉得上面页面不好看,还可以使用knife4j增强。

官网:knife4j (xiaominfo.com)

使用方法很简单,只需要加入下面依赖。

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-ui</artifactId>
    <version>2.0.5</version>
</dependency>

重新启动项目,这次打开这个网页:http://localhost:8080/doc.html#/home

好看!

生成md接口文档

导入依赖:

<!--swagger2markup-->
 <dependency>
     <groupId>io.github.swagger2markup</groupId>
     <artifactId>swagger2markup</artifactId>
     <version>1.3.1</version>
 </dependency>
 <dependency>
     <groupId>ch.netzwerg</groupId>
     <artifactId>paleo-core</artifactId>
     <version>0.10.2</version>
 </dependency>
 <dependency>
     <groupId>io.vavr</groupId>
     <artifactId>vavr</artifactId>
     <version>0.9.2</version>
 </dependency>

生成文档的代码写在测试里即可:

 import com.example.helloSwagger.HelloSwaggerApplication;
 import io.github.swagger2markup.Language;
 import io.github.swagger2markup.Swagger2MarkupConfig;
 import io.github.swagger2markup.Swagger2MarkupConverter;
 import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
 import io.github.swagger2markup.markup.builder.MarkupLanguage;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.test.context.junit4.SpringRunner;
 ​
 import java.net.URL;
 import java.nio.file.Paths;
 ​
 @SpringBootTest(classes = HelloSwaggerApplication.class,webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
 @RunWith(SpringRunner.class)
 public class testDocs
 {
     // 群组名称
      final String group = "group1";
 ​
     /**
      * 生成md格式文档
      * @throws Exception
      */
     @Test
     public void generateMarkdownFile() throws Exception {
         Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                 // 指定文件格式为markdown
                 .withMarkupLanguage(MarkupLanguage.MARKDOWN)
                 // 指定语言为中文
                 .withOutputLanguage(Language.ZH)
                 // 生成参数示例
                 .withGeneratedExamples()
                 // 生成请求体
                 .withFlatBody()
                 
                 .withoutInlineSchema()
                 .build();
 ​
         // 获取接口数据的url,请求方式是get,若没有分组则不需要group参数
         URL apiUrl = new URL("http://localhost:8080/v2/api-docs?group="+group);
 ​
         // 指定文件名称
         String markdownFileName = "src/docs/markdown/generated/api";
 ​
         // 指定获取接口数据的url
         Swagger2MarkupConverter.from(apiUrl)
                 // 指定配置信息
                 .withConfig(config)
 ​
                 .build()
                 //指定生成目录下生成指定文件
                 .toFile(Paths.get(markdownFileName));
     }
 }

如果直接启动测试代码,可能会爆红。。

 java.lang.IllegalStateException: Failed to load ApplicationContext

实际上可能是你前面编写的Springboot项目还在启动导致的,关掉再重启即可。。

再次启动,

真香 ~ ~ ~

参考网站

grinch2113/SwaggerDemo: Swagger的demo项目 (github.com)

SpringBoot更新到2.6.0启动报错 Failed to start bean ‘documentationPluginsBootstrapper‘ 问题处理_CHQIUU的博客-CSDN博客

齐全的swagger注解介绍 - 知乎 (zhihu.com)

给你的Swagger文档换套附魔皮肤吧 - codermy - 博客园 (cnblogs.com)

感谢!

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot项目中整合Swagger UI,可以按照以下步骤进行操作: 1. 在项目的Maven或Gradle配置中添加Swagger依赖,例如: ```xml <!-- Maven --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` ```groovy // Gradle implementation 'io.springfox:springfox-boot-starter:3.0.0' ``` 2. 创建一个配置类(例如`SwaggerConfig`)并添加`@Configuration`和`@EnableSwagger2`注解,示例如下: ```java import springfox.documentation.swagger2.annotations.EnableSwagger2; import org.springframework.context.annotation.Configuration; @Configuration @EnableSwagger2 public class SwaggerConfig { // 配置内容 } ``` 3. 在配置类中,可以使用`Docket`来配置Swagger的基本信息,例如设置API的标题、描述等,示例如下: ```java import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.RequestHandlerSelectors; import org.springframework.context.annotation.Bean; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controllers")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API Documentation") .description("API Documentation for my project") .version("1.0.0") .build(); } } ``` 4. 启动项目,访问`http://localhost:8080/swagger-ui.html`即可查看Swagger UI界面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值