Swagger与Springboot项目进行集成很简单,首先就是添加一些maven的jar包依赖,然后添加一些swagger的相关配置,之后启用swagger在Controller的类或方法上添加一些swagger的描述信息,最后启动项目访问swagger的ui地址进行接口测试即可。具体步骤如下:
目录
一、POM依赖
二、添加Swagger的配置文件SwaggerConfig.java
三、在main方法中开启对Swagger的支持
四、创建一个Controller文件描述一些接口
五、启动项目后访问UI地址
六、Swagger中常用的一些注解
七、Swagger在使用中的一些常见问题
1、时间格式化问题
2、获取Swagger生成的接口json文档
3、利用Swagger插件自动生成html或pdf格式的接口文档
io.springfox
springfox-swagger2
2.6.1
io.springfox
springfox-swagger-ui
2.6.1
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
//通过参数构造器为swagger添加对header参数的支持,如果不需要的话可以删掉
ParameterBuilder ticketPar = new ParameterBuilder();
List pars = new ArrayList();
ticketPar.name("loginToken").description("用户的Token信息")
.modelRef(new ModelRef("string")).parameterType("header")
.required(false).build(); //header中的loginToken参数现在设置为非必填,传空也可以
pars.add(ticketPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//扫描的swagger接口包路径
.apis(RequestHandlerSelectors.basePackage("com.mengfei.learn.swaggercontroller"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars); //不需要添加全局参数时这一行可以删掉
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Springboot利用swagger构建api文档")
.description("简单优雅的restful风格 http://blog.csdn.net/")
.termsOfServiceUrl("http://blog.csdn.net/")
.version("1.0")
.build();
}
}
//启用Swagger2的配置
@EnableSwagger2
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
@Controller
@RequestMapping("/user")
public class SwaggerControllerTest {
//Swagger UI 查看地址:http://localhost:8080/swagger-ui.html
@Autowired
private UserMapper userMapper;
// 演示:路径参数入参,以及注释换行(注释换行使用两个空格和一个\n)
@ApiOperation(value = "获取用户信息",notes = "oid 用户主键 \ncreated 创建时间")
@ApiImplicitParam(name = "oid",value = "用户ID",required = true, dataType = "long",paramType = "path")
@RequestMapping(value = "/getUser/{oid}",method = RequestMethod.GET)
@ResponseBody
public ResponseEntity getUser(@PathVariable(value = "oid") Long oid){
UserBase userBase = userMapper.findById(oid).get();
return ResponseEntity.ok(userBase);
}
// 演示:入参使用json格式的对象(使用@RequestBody注解,paramType可省略,name名与对象名保持一致)
@ApiOperation(value = "创建用户")
@ApiImplicitParam(name = "user",value = "用户的实体信息",required = true,dataType = "UserBase",paramType = "body")
@RequestMapping(value = "/addUser",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity addUser(@RequestBody UserBase user){
UserBase save = userMapper.save(user);
return ResponseEntity.ok(save);
}
// 演示:表单入参使用DTO对象,以及文件上传
// 对象入参可以使用@ApiImplicitParams注解描述,也可在对象属性上添加@ApiModelProperty注解描述,但文件入参比较特殊不能
// 用@ApiModelProperty来描述。@ApiModelProperty的描述示例如下:
// 数据状态(0删除,1正常)
// @ApiModelProperty(value = "数据状态00",name = "state",notes = "0删除,1正常",required = true,dataType = "int")
// private Integer state; //getter setter …)
@ApiOperation(value = "更新用户信息")
@ApiImplicitParams({
//@ApiImplicitParam(name = "userInfoDesc",value = "用户信息描述",required = true,dataType = "string",paramType = "query"),
//@ApiImplicitParam(name = "state",value = "数据状态",required = true,dataType = "int",paramType = "query"),
@ApiImplicitParam(name = "userLogo",value = "用户头像",required = true,dataType = "file",paramType = "form"),
})
@RequestMapping(value = "/updateUser",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity updateUser(UserInfoRequestDTO requestDTO){
String userLogoName = requestDTO.getUserLogo().getOriginalFilename();
System.out.println(userLogoName);
return ResponseEntity.ok("OK");
}
// 演示:表单入参使用DTO对象,文件入参单独列出(文件入参也可在参数列表中直接使用@ApiParam注解来描述)
@ApiOperation(value = "更新用户信息2")
@RequestMapping(value = "/updateUser2",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity updateUser2(UserInfoRequestDTO2 requestDTO,
@ApiParam(value = "用户头像",name = "userLogo", required = true) MultipartFile userLogo){
String userLogoName = userLogo.getOriginalFilename();
System.out.println(userLogoName);
return ResponseEntity.ok("OK");
}
// 演示:表单入参文件数组,上传多个文件
// 在@RequestMapping中添加consumes = "multipart/form-data"可以支持多文件数组上传,否则Swagger将自动将Content-Type设置
// 为application/json,但设置之后Swagger还是无法选择多个文件进行接口测试的,只是显示可以传递文件数组,这时可以采用Postman
// 或RestClient等接口测试工具进行接口测试,多文件上传建议使用@ApiParam注解
@ApiOperation(value = "更新用户信息3")
@RequestMapping(value = "/updateUser3",method = RequestMethod.POST,consumes = "multipart/form-data")
@ResponseBody
public ResponseEntity updateUser3(@ApiParam(value = "用户头像列表",name = "userLogos",required = true) MultipartFile[] userLogos){
for(MultipartFile userLogo:userLogos){
String userLogoName = userLogo.getOriginalFilename();
System.out.println(userLogoName);
}
return ResponseEntity.ok("OK");
}
}
http://localhost:8080/swagger-ui.html
可以查看到类似于如下所示的页面:
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数,描述整个对象的信息
@ApiProperty:用对象接收参数时,描述对象的一个属性
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息
@ApiImplicitParam:一个请求参数描述
@ApiImplicitParams:多个请求参数描述
在实体类的属性上加上两个注解,@JsonFormat注解用于入参和出参的时间格式化,@ApiModelProperty的example属性用于swagger的文档描述信息时间格式化。示例如下:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
@ApiModelProperty(example = "2018-04-26 00:00:00")
访问:http://localhost:8080/v2/api-docs
通过浏览器右键另存为json文件,当然你也可以写个程序从这个接口获取到数据后自动生成json文件。
请参考:Swagger使用(二)—— 利用swagger2markup生成离线的html和pdf接口文档