上一篇: 微服务(十二)—— 配置中心(backend-config-server).
1. 介绍
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务,可以在线生成和功能测试。
2. Swagger使用
如何将Swagger集成到项目中呢?
2.1 依赖
首先需要加入swagger的依赖
<!-- swagger 依赖-->
<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>
2.2 编写Swagger配置类
package com.aiun.common.config;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(true)
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build();
}
/**
* 基本信息的配置,信息会在 Api 文档上显示
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("订单管理系统测试接口文档")
.description("订单管理系统所有子系统相关的测试接口文档")
.version("v1.0")
.termsOfServiceUrl("http://localhost:8084")
.version("1.0")
.build();
}
}
如果想用在开发和测试环境开启swagger,可以这样配置 Docket。
@Bean
public Docket createRestApi(Environment environment){
// 设置要显示的 Swagger 环境
Profiles profiles = Profiles.of("dev", "test");
// 通过 acceptsProfiles 方法判断是否在自己设定的环境当中
boolean show = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(show) // 是否启用 swagger
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build();
}
配置完成后,在需要的接口加注释说明就好。
首先是 Controller层
在类上使用@Api 注解
@Api(tags = "订单系统相关接口")
tags说明信息
在方法上使用@ApiOperation注解
@ApiOperation(value = "用户登录", notes = "用户登录")
如下:
@Api(tags = "用户系统相关接口")
@RestController
@RequestMapping("/user/")
public class UserController {
@Autowired
private IUserService iUserService;
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 用户登录
* @param username 用户名
* @param password 密码
* @return 返回登录信息
*/
@PostMapping("login")
@ApiOperation(value = "用户登录", notes = "用户登录")
public ServerResponse<User> login(String username, String password) {
ServerResponse<User> response = iUserService.login(username, password);
return response;
}
//.......
}
在数据库对应的实体类使用@ApiModel 注解
@ApiModel(value = "user对象", description = "用户表")
在实体类的属性上使用 @ApiModelProperty 注解
@ApiModelProperty(value = "用户名")
如下:
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Accessors(chain = true)
@ApiModel(value = "user对象", description = "用户表")
public class User implements Serializable {
@ApiModelProperty(value = "用户表 主键")
private Integer id;
@ApiModelProperty(value = "用户名")
private String username;
//......
}
然后启动项目,在浏览器输入http://localhost:8084/backend-user/swagger-ui.html,地址就会出现UI界面
每一个接口都可以测试。