这篇文章将为大家详细讲解有关SpringBoot中如何使用Swagger,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
创新互联客户idc服务中心,提供资阳托管服务器、成都服务器、成都主机托管、成都双线服务器等业务的一站式服务。通过各地的服务中心,我们向成都用户提供优质廉价的产品以及开放、透明、稳定、高性价比的服务,资深网络工程师在机房提供7*24小时标准级技术保障。
项目结构

配置文件
@Configuration
@EnableSwagger2
public class Swagger2Config {
//swagger2的配置文件,可以配置swagger2的一些基本的内容,比如扫描的包等等
@Bean
public Docket defaultApi(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).groupName("默认分组").select()
.apis(RequestHandlerSelectors.basePackage("com.chenwenhuan.springbootlearning.controller"))
.paths(PathSelectors.any()).build();
}
// 预览地址:http://localhost:8082/swagger-ui.html#/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("整合swagger构建测试系统api文档")
.description("接口访问地址:http://localhost:8082/")
.termsOfServiceUrl("http://localhost:8082/")
.version("1.0")
.build();
}
}
pom.xml 新增依赖
io.springfox springfox-swagger2 2.7.0 io.springfox springfox-swagger-ui 2.7.0
Controller注解
@Api(value="用户api", tags="用户api")
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@GetMapping("/findAll")
public List findAll(){
return userService.findAll();
}
@ApiOperation(value="获取用户信息", notes="根据url的id来获取信息")
@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户ID", paramType = "query",required = true)})
@GetMapping("/getUser")
public User getUser(@RequestParam int id){
return userService.getUserById(id);
}
@PostMapping("/creatUser")
public void creatUser(User user){
System.out.println(user);
userService.insert(user);
}
@PostMapping("/creatUserList")
public void creatUserList(@RequestBody List list){
userService.insertList(list);
}
}
启动项目访问预览地址 http://localhost:8082/swagger-ui.html#/,效果如下。(可以看出此处很多信息都源自配置Swagger2Config)
示例1

输入参数点击Try it out!,可以查看返回码和返回数据

示例2:
参考右边提示,按格式输入Json格式的对象数组

示例3:
controller需要注解 paramType = "query",否则需要按Example Value 格式输入。required:是否必输
@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户ID", paramType = "query",required = true)})
关于SpringBoot中如何使用Swagger就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。