SpringBoot项目使用Swagger2搭建Restful API在线文档的简单应用

mac2022-06-30  20

Restful API文档管理框架主要有 Swagger smart-doc apidoc等,这三个都尝试使用过,还是Swagger好用。Swagger是一个功能强大的在线API文档框架,目前它的版本是2.x,所以称为Swagger2。Swagger2提供了在线文档的查阅和测试功能。SpringBoot中集成了Swagger2,下面我们来一个简单的使用。 首先得有一个现成的SpringBoot web项目。 1、引入pom依赖

<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> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.6</version> </dependency>

上面三个依赖前两个是必须的,第三个依赖引入了 bootstrap-ui 为了更美观的展示在线文档。 2、配置Swagger2 SwaggerConfig可以就和WebApplication并列: SwaggerConfig配置内容:

@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean(value = "xxxApi") public Docket xxxApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) //接口名称 .groupName("xx接口") .select() //basePackage里要写Controller类所在的包 .apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.web")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() //标题 .title("xxxx RESTful APIs") //简介 .description("xxxxx") //作者个人信息 .contact(new Contact("xxxxxx", "", "")) //版本 .version("1.0") .build(); } }

3、在Controller层配置注解 3.1 Controller类上配置注解

@Api(value = "xxx控制类",tags = "xxx控制类")

3.2 Controller类的方法上配置注解

@ApiOperation(value="xxx", httpMethod = "GET", notes="xxx") @ApiImplicitParams({ @ApiImplicitParam(name="param1",value="参数1",paramType = "query",dataType = "String",required=true), @ApiImplicitParam(name="param2",value="参数2",paramType = "query",dataType = "String",required=true), @ApiImplicitParam(name="param3",value="参数3",paramType = "query",dataType = "String",required=false) })

4、返回的实体类注解 实体类加注解,方便查看返回参数的含义 类名上面加注解 @ApiModel 变量名上加注解@ApiModelProperty(value = “xxx”, required = true)

启动项目,输入http://localhost:{项目端口号}/{context-path}/swagger-ui.html,浏览器就会生成接口文档 bootstrap-ui在线文档:http://localhost:{项目端口号}/{context-path}/doc.html

以上只是简单的使用,附上几篇文章供参考,尤其是要理解注解里的一些配置参数含义:

https://segmentfault.com/a/1190000019273239https://blog.csdn.net/moshowgame/article/details/80265480https://blog.csdn.net/qq_35620501/article/details/92223892https://www.cnblogs.com/fengli9998/p/7921601.html
最新回复(0)