一、什么是swagger?
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 restful 风格的 Web 服务。
总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。
二、如何使用swagger?
本文主要介绍在springboot中swagger的使用。
1、导入依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
通过Swagger UI生成网页版的接口文档,可以在上面做简单的接口调试 。功能还是比较强大的。
2、配置swagger
在config包下面新建一个class类。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(Environment environment) {
//设置要显示的swagger环境
Profiles profiles = Profiles.of("dev");
//判断自己是否处于设定的环境中
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).groupName("daodao");
//通过flag判断该环境是否能访问swagger
//.enable(flag)
//.select()
//any():扫描全部
//none():都不扫描
//basePackage():扫描指定的包
//withClassAnnotation():扫描类上的注解,参数是注解的反射对象(restController)
//withMethodAnnotation:扫描方法上的注解
// .apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))
// //过滤什么路径
// .paths(PathSelectors.ant("/daodao/**"))
// .build();
}
public ApiInfo apiInfo() {
Contact contact = new Contact("刀刀","localhost:8080","123455@qq.com");
return new ApiInfo("刀刀",
"即使再小的帆也能远航",
"1.0",
"localhost:8080",
contact,
"apache2.0",
"wangjiansuoyou",
new ArrayList<>());
}
}
配置完之后显示效果如下:登入http://localhost:8080/swagger-ui.html查看
3、作一个简单测试
实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(description = "新闻")
public class News implements Serializable {
@ApiModelProperty(value = "新闻标题",name = "title")
private String title;
@ApiModelProperty(value = "新闻内容",name = "content")
private String content;
}
controller层(service和dao层就不写了,简单的查询)
@RestController
public class NewsController {
@Autowired
private INewsService newsService;
@GetMapping("/news")
public List queryAll() throws Exception {
ModelAndView m = new ModelAndView();
List<News> newsList = newsService.queryAll();
return newsList;
}
//要测试的方法
@PostMapping("/newsByTitle")
public String queryByTitle(@ApiParam @RequestBody String title) throws Exception {
System.out.println("title is "+title);
String content = newsService.queryByTitle(title);
System.out.println(content);
return content;
}
}
测试一下:
总的来说,swagger的基本用法就是如此了。不是很难。
那么,swagger的优点也是可以看得到的,便利了前后端分离,在线自动生成文档等。但是主要在生产环境中要将swagger隐藏或者删除,否则会有安全隐患。
4、swagger常用注解
常用注解:
- @Api()用于类;
表示标识这个类是swagger的资源 - @ApiOperation()用于方法;
表示一个http请求的操作 - @ApiParam()用于方法,参数,字段说明;
表示对参数的添加元数据(说明或是否必填等) - @ApiModel()用于类
表示对类进行说明,用于参数用实体类接收 - @ApiModelProperty()用于方法,字段
表示对model属性的说明或者数据操作更改 - @ApiIgnore()用于类,方法,方法参数
表示这个方法或者类被忽略 - @ApiImplicitParam() 用于方法
表示单独的请求参数 - @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam