软件编程
位置:首页>> 软件编程>> java编程>> Spring boot配置 swagger的示例代码

Spring boot配置 swagger的示例代码

作者:XiaoRunStar  发布时间:2023-03-07 13:10:44 

标签:Spring,boot,配置,swagger

为什么使用Swagger

    在实际开发中我们作为后端总是给前端或者其他系统提供接口,每次写完代码之后不可避免的都需要去写接口文档,首先写接口文档是一件繁琐的事,其次由接口到接口文档需要对字段、甚至是排版等。再加上如果我们是为多个系统提供接口时可能还需要按照不同系统的要求去书写文档,那么有没有一种方式让我们在开发阶段就给前端提供好接口文档,甚至我们可以把生成好的接口文档暴露出去供其他系统调用,那么这样我只需要一份代码即可。

Spring boot配置 swagger

 1.导入maven依赖


<!--配置swagger-->
       <dependency>
           <groupId>io.springfox</groupId>
           <artifactId>springfox-swagger2</artifactId>
           <version>2.6.1</version>
       </dependency>
       <dependency>
           <groupId>io.springfox</groupId>
           <artifactId>springfox-swagger-ui</artifactId>
           <version>2.6.1</version>
       </dependency>

<!--swagger第三方ui-->
       <dependency>
           <groupId>com.github.xiaoymin</groupId>
           <artifactId>swagger-bootstrap-ui</artifactId>
           <version>1.9.6</version>
       </dependency>

2.swagger配置类


@EnableSwagger2                // Swagger的开关,表示已经启用Swagger
@Configuration                 // 声明当前配置类
public class SwaggerConfiguration  {

@Value("${swagger.basePackage}")
   private String basePackage;       // controller接口所在的包

@Value("${swagger.title}")
   private String title;           // 当前文档的标题

@Value("${swagger.description}")
   private String description;         // 当前文档的详细描述

@Value("${swagger.version}")
   private String version;         // 当前文档的版本

@Bean
   public Docket createRestApi() {
       return new Docket(DocumentationType.SWAGGER_2)
               .apiInfo(apiInfo())
               .select()
               .apis(RequestHandlerSelectors.basePackage(basePackage))
               .paths(PathSelectors.any())
               .build();
   }

private ApiInfo apiInfo() {
       return new ApiInfoBuilder()
               .title(title)
               .description(description)
               .version(version)
               .build();
   }

}

3.application.yml


# 配置swagger
swagger:
 basePackage: com.xx.demo.controller #包名
 title: 标题  #标题
 description: 项目文档 #描述
 version: V1.0  #版本号

4.在controller里使用


@Api(tags = {"测试类"})
@RestController
@RequestMapping("/test")
public class TestController {
   @ApiOperation(value = "测试方法")
   @GetMapping("/xrx")
   public String xrx() {
       return "hello";
   }
}

5.访问swagger

http://localhost:8080/swagger-ui.html
http://localhost:8080/doc.html

Spring boot配置 swagger的示例代码

来源:https://blog.csdn.net/weixin_45223244/article/details/120351028

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com