在Sping开发REST接口服务时,api文档是不可缺少的一个重要部分。Swagger框架定义了完整的REST接口文档规范,提供了强大的页面测试功能,能够调试和可视化API接口服务,并且将文档融合到代码中,让维护文档和修改代码整合为一体,使得修改代码逻辑的同时方便的修改文档说明。
Spring集成Swagger只需3步配置,就能在线生成接口文档,调试API功能。
功能要点 |
||
SpringBoot集成Swagger |
pom.xml |
引入Swagger依赖:springfox-swagger2, springfox-swagger-ui |
SwaggerConfig.java |
配置Swagger信息和扫描包路径 |
|
@Api(tags={“xxx”}) @ApiOperation(“xxx”) @ApiParam(“xxx”) ...... |
||
http://localhost:8011/swagger-ui.html |
l 代码
Github下载:https://github.com/jextop/Starterapi/
l SpringBoot集成Swagger
1. 在pom.xml中添加Swagger依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
2. 添加SwaggerConfig.java,配置文档信息和扫描包路径
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.starter"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot搭建分布式Web服务脚手架")
.license("Github开源项目")
.licenseUrl("https://github.com/jextop")
.build();
}
}
- 不添加这些注解时,Swagger自动生成在线文档将使用默认信息。
@Api(tags = {"用户管理"})
@RestController
@RequestMapping("/")
public class SecurityController {
@ApiOperation("用户登录")
@GetMapping(value = "/login")
public Object login(
@RequestParam(required = false) String username,
@ApiParam("密码计算公式:md5(b64(username + password)") @RequestParam(required = false) String password
) {
// todo
}
}
l 启动Spring项目,打开文档页面
1. http://localhost:8011/swagger-ui.html
2. 展开API信息,点击按钮”Try it out!”,调试接口功能。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。