SpringBoot集成swagger2教程
1 第一步添加依赖
maven 引入pom 直接集成spring boot
com.spring4all
swagger-spring-boot-starter
1.9.1.RELEASE
2 配置
创建配置类 /test/.* 以路径分组(注意此类要能被Spring ioc扫描到)
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket testConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("testApi")
.apiInfo(new ApiInfoBuilder()
.title("管理系统的API文档")
.description("本文档描述了api接口定义")
.version("1.0")
.contact(new Contact("张凯强", "https://zhangkaiq.gitee.io/", "862166318@qq.com"))
.build())
.select()
.paths(Predicates.and(PathSelectors.regex("/test/.*")))
.build();
}
}
3 注解用法
实体类Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "test对象",description = "test对象信息")
public class Test {
@ApiModelProperty(value = "描述信息id",name = "id",example = "1")
private Long id;
@ApiModelProperty(value = "描述信息name",name = "name",example = "张凯强")
private String name;
@ApiModelProperty(value = "描述信息age",name = "age",example = "20")
private Integer age;
}
控制层Controller
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/index")
@ApiOperation("没有参数")
public Test index(){
return new Test(1L,"张凯强",20);
}
@GetMapping("/getTest")
@ApiOperation("GET传参")
public Test getTest(@ApiParam(value = "id",required = true,defaultValue = "10")
@RequestParam("id")Long id){
return new Test(id,"张凯强",20);
}
@ApiOperation("POST传参")
@PostMapping("/addTest")
public Test addTest(@RequestBody Test test){
return test;
}
@ApiOperation("路径传参")
@DeleteMapping("/deleteTest/{id}")
public Long deleteTest(@ApiParam(value = "id",required = true,defaultValue = "10")
@PathVariable("id")Long id){
return id;
}
}
@ApiModel注解实体类(Model)
@ApiModel(value = "test对象",description = "test对象信息")
public class Test{}
@ApiModelProperty注解属性(实体类字段)
@ApiModelProperty(value = "描述信息id",name = "id",example = "1")
private Long id;
@Api 注解@Controller 层也可@RestController
@Api(value = "测试控制层",description = "测试控制层接口API描述!")
public class TestController{}
@ApiOperation注解方法Controller 的方法
@ApiParam 注解参数
@ApiOperation("测试方法")
@GetMapping("/test")
public ObjectJson test(@ApiParam(value = "id", required = true, defaultValue = "1")
@RequestParam(value = "id") Long id)
4 启动测试结果
swagger2页面地址 协议://地址:端口/加项目名/swagger-ui.html
http://localhost:8080/swagger-ui.html
无参GET请求
有参数GET请求
有参POST请求
路径参DELETE请求
有问题质询QQ:248048521,欢迎技术交流