swargger2實(shí)現(xiàn)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構(gòu)建RESTful APIs")
.description("spring boot 個人測試")
// .termsOfServiceUrl("")
.contact("程序猿DD")
.version("1.0")
.build();
}
}
文件上傳配置:
@ApiOperation(value = "發(fā)票上傳", notes = "發(fā)票上傳")
@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風(fēng)格接口配置:
@ApiOperation(value="獲取用戶信息", notes="根據(jù)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" 否則調(diào)用時出現(xiàn)不能轉(zhuǎn)換的錯誤
需要源碼的可以評論留下你的微信號