swargger2实现API接口测试
1.maven配置:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
2.在Application同级目录下新建Swagger2类:
@Configuration
@EnableSwagger2 //启用swagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.yonyou.myspringboot"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("spring boot 个人测试")
// .termsOfServiceUrl("")
.contact("程序猿DD")
.version("1.0")
.build();
}
}
文件上传配置:
@ApiOperation(value = "发票上传", notes = "发票上传")
@ApiImplicitParam(name = "assetId", value = "凭证ID", required = true, dataType = "String", paramType = "String")
@RequestMapping(value = "uploadingFiles", method = RequestMethod.POST , consumes = "multipart/form-data")
@ResponseBody
public BaseResult uploadFile(String assetId, @ApiParam(value = "上传的文件", required = true) @RequestParam("jarFile") MultipartFile jarFile) throws IOException {
if(jarFile != null){
String name = jarFile.getName();
long size = jarFile.getSize();
log.debug("assetId:{},name:{}, size:{}", assetId, name, size);
System.out.println(new String(jarFile.getBytes()));
return BaseResult.OK(new String(jarFile.getBytes()));
}
return BaseResult.Error();
}
rest风格接口配置:
@ApiOperation(value="获取用户信息", notes="根据id获取用户信息", httpMethod = "GET")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
@RequestMapping(path = "consumingRest/{id}")
public User getUser(@PathVariable int id){
User user = new User();
user.setId(id);
user.setAge(20);
user.setName("张三");
return user;
}
dataType = “Integer”, paramType = “path” 否则调用时出现不能转换的错误
需要源码的可以评论留下你的微信号