swagger的使用之二swagger在idea的使用


首先在idea引入后创建一个config 包并添加一个 SwaggerConfig

@Configuration @EnableSwagger2 public class swagger2 { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2)
          .apiInfo(apiInfo()) .select()
          .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any())
          .build();
} private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("Springboot中使用Swagger文档") .description("更多信息请等待更新") .version("1.0") .build(); } }

补充:

//此包路径下的类,才生成接口文档
.apis(RequestHandlerSelectors.basePackage("com.bike.controller"))
//加了ApiOperation注解的类,才生成接口文
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))

 

 


启动的效果

 

 

创建接口controller

首先这里涉及到多个API

1.@Api注解可以用来标记当前Controller的功能。

2.@ApiOperation注解用来标记一个方法的作用。
3.@ApiImplicitParam注解用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入。
如果有多个参数,则需要使用多个@ApiImplicitParam注解来描述,多个@ApiImplicitParam注解需要放在一个

4.@ApiImplicitParams注解中。需要注意的是,@ApiImplicitParam注解中虽然可以指定参数是必填的,但是却不能代替@RequestParam(required = true),前者的必填只是在Swagger2框架内必填,抛弃了Swagger2,这个限制就没用了,所以假如开发者需要指定一个参数必填,@RequestParam(required = true)注解还是不能省略。

如:

@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping(value="/users") // 通过这里配置使下面的映射都在/users下,可去除
public class UserController {

@ApiOperation(value = "查询用户",notes = "根据id查询用户")
//描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,required = true表示如果swagger测试为必填,defaultValue默认值
@ApiImplicitParam(name= "id",value = "用户id",required = true,defaultValue = "66")
@GetMapping("/user")
public User getUserById(Integer id){
User user = new User();
user.setId(id);
return user;
}
@ApiOperation(value = "删除用户",notes = "根据id删")
@ApiImplicitParam(name = "id",value = "用户id",required = true,defaultValue = "55")
@ApiResponses({
@ApiResponse(code = 200,message = "删除成功"),
@ApiResponse(code = 500,message = "失败")
})
@DeleteMapping("/user/{id}")
public void deleteUserById(@PathVariable Integer id){
System.out.println("deleteUserById:"+id);
}

@PostMapping("/user")
@ApiOperation(value = "添加用户",notes = "添加用户接口")
public User addUser(@RequestBody User user) {
return user;

}

@PutMapping("/user")
@ApiImplicitParams({
@ApiImplicitParam(name="id",value = "用户id",required = true,defaultValue = "77"),
@ApiImplicitParam(name="username",value = "用户名",required = true,defaultValue = "taoge"),
})
@ApiOperation(value = "更新用户",notes= "根据id更新用户的接口")
// @ApiIgnore //表示忽略生成此接口
public User updateUserById(@RequestBody User user) {
return user;
}
}
在实体类中的用法
@Data
@ApiModel(value = "用户表参数说明",description = "用户表参数说明")
public class User {
@ApiModelProperty(value = "用户id")
private Integer id;
@ApiModelProperty(value = "用户姓名")
private String name;
@ApiModelProperty(value = "用户年龄")
private Integer age;
}
效果如下:

 

 Controller类效果

 

 

 

 

 

 实体类效果

 

 

 

 



 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM