Swagger介绍
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务 ( https://swagger.io/ ) 。 它的主要作用是:
- 1. 使得前后端分离开发更加方便,有利于团队协作
- 2. 接口的文档在线自动生成,降低后端开发人员编写接口文档的负担
- 3. 功能测试
Spring 已经将 Swagger 纳入自身的标准,建立了 Spring-swagger 项目,现在叫 Springfox 。通过在
项目中引入 Springfox ,即可非常简单快捷的使用 Swagger 。
SpringBoot集成Swagger
1、引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
2、在工程的application.propertis中配置swagger的启动开关
# 开启swagger
swagger.enable=true
3、在工程的config包中添加一个配置类
@Configuration //声明是一个配置类
@ConditionalOnProperty(prefix = "swagger",value = {"enable"},havingValue = "true")
@EnableSwagger2 //开启swagger注解支持
public class SwaggerConfiguration {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInfo())
.select()
// 要扫描的API(Controller)基础包
.apis(RequestHandlerSelectors.basePackage("cn.awen.wanxinp2p"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo buildApiInfo() {
Contact contact = new Contact("awen","","");
return new ApiInfoBuilder()
.title("该微服务的功能介绍")
.description("微服务中该接口的功能介绍")
.contact(contact)
.version("1.0.0").build();
}
}
4、测试
@RestController
@Api(value = "统一账户服务的API")
public class AccountController implements AccountAPI {
@Autowired
private AccountService accountService;
@ApiOperation("校验手机号和验证码")
@ApiImplicitParams({@ApiImplicitParam(name = "mobile", value = "手机号", required = true,
dataType = "String"),
@ApiImplicitParam(name = "key", value = "校验标识", required = true, dataType = "String"),
@ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String")})
@Override
@GetMapping("/mobiles/{mobile}/key/{key}/code/{code}")
public RestResponse<Integer> checkMobile(@PathVariable String mobile,
@PathVariable String key,
@PathVariable String code) {
return RestResponse.success(accountService.checkMobile(mobile,key,code));
}
}
Swagger常用注解
在 Java 类中添加 Swagger 的注解即可生成 Swagger 接口文档,常用 Swagger 注解如下:
启动wanxinp2p-consumer-service服务工程,用浏览器访问:http://localhost:53010/consume
r/swagger-ui.html
本文含有隐藏内容,请 开通VIP 后查看