前言
SwaggerUI可以说是一个非常好用的API文档工具,是前后端分离开发模式下的必备工具、具体实现及部分干货知识如下
导入依赖
<!-- RESTful APIs swagger2 -->
<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>
编写配置类
/**
* swagger-ui的配置
* api页面 /swagger-ui.html
* 如controller在不同的包中,@ComponentScan(basePackages = {"*","..."})
* @author 郑杰
* @date 2018/10/28 12:44:04
*/
@Configuration
@EnableSwagger2
@ComponentScan(basePackages = {"me.zhengjie.controller"})
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("RESTful API")
.termsOfServiceUrl("https://gitee.com/hgpt/SpringBoot_All")
.description("Spring Boot 使用Swagger2构建RESTful APIs")
.version("1.0")
.build();
}
}
编写实体及控制器
User.class
@Entity
@Table(name = "user")
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private Integer age;
private String sex;
}
UserController.class
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserRepo userRepo;
@GetMapping
public ResponseEntity findAll(@PageableDefault(value = 10, sort = {"id"}) Pageable pageable){
return ResponseEntity.ok(userRepo.findAll(pageable));
}
@PostMapping
public ResponseEntity save(@RequestBody User user){
userRepo.save(user);
return new ResponseEntity(HttpStatus.CREATED);
}
@PutMapping
public ResponseEntity update(@RequestBody User user){
userRepo.save(user);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
@DeleteMapping(value = "/{id}")
public ResponseEntity del(@PathVariable Long id){
userRepo.deleteById(id);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
}
启动项目查看
swagger默认启动地址:
项目地址后面加/swagger-ui.html 如:http://localhost:8080/swagger-ui.html#
查看效果
扩展知识
扩展支持Token传入
修改Swagger2Config中的createRestApi方法
@Bean
public Docket createRestApi() {
ParameterBuilder ticketPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
ticketPar.name("Authorization").description("token")
.modelRef(new ModelRef("string"))
.parameterType("header")
.defaultValue("Bearer ")
.required(true)
.build();
pars.add(ticketPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build()
.globalOperationParameters(pars);
}
查看效果
@ApiModelProperty
此注解加入在实体类中的字段上,如:
@ApiModelProperty(hidden = true)
private Long id;
我们新增时ID是自增的,所以就不需要显示ID,这个时候不隐藏掉可能会误导前端人员调用,通过此注解可以在User的数据结构中隐藏ID属性
效果如下:
@ApiOperation
该注解是加在方法上面的,用于给API增加说明
@ApiOperation(value="创建用户", notes="根据User对象创建用户")
@PostMapping
public ResponseEntity save(@RequestBody User user){
userRepo.save(user);
return new ResponseEntity(HttpStatus.CREATED);
}
效果如下:
@ApiImplicitParam
该注解是给接口的属性添加描述
@ApiOperation(value="删除用户", notes="根据UserId删除用户")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@DeleteMapping(value = "/{id}")
public ResponseEntity del(@PathVariable Long id){
userRepo.deleteById(id);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
效果如下:
如果有多个属性,可以使用
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
@ApiImplicitParam(name = "age", value = "用户年龄", required = true, dataType = "Integer")
})
参考信息
项目源码
github:https://github.com/dqjdda/SpringBoot_All
码云:https://gitee.com/hgpt/SpringBoot_All
开源后台管理系统:
欢迎体验Aurora
github: https://github.com/dqjdda/Aurora
码云: https://gitee.com/hgpt/Aurora