Swagger是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。
一、使用介绍
什么是 Swagger?
Swagger的目标是为REST APIs 定义一个标准的,与语言无关的接口,使人和计算机在看不到源码或者看不到文档或者不能通过网络流量检测的情况下能发现和理解各种服务的功能。当服务通过Swagger定义,消费者就能与远程的服务互动通过少量的实现逻辑。类似于低级编程接口.
如何集成Swagger-springmvc到我们的项目中?
依赖:
maven
<!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
使用:
创建config
@Configuration //写config都要加@Configuration
@EnableSwagger2 //开启swagger2
public class SwaggerConfig {
//配置多个分组 多个Docket实例即可
@Bean
public Docket docket1() {
return new Docket(DocumentationType.SWAGGER_2).groupName("琪琳");
}
//配置swagger的docket的bean实例
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("凯莎")
.select()
//RequestHandlerSelectors 配置要扫描接口的方式
//.basePackage 指定扫描的包
.apis(RequestHandlerSelectors.basePackage("com.wu.swagger.controller"))
.build();
}
//配置Swagger 信息=apiInfo
private ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("不想学了啊", "", "");
return new ApiInfo("我自己的SwaggerAPI文档",
"神圣凯莎知识宝库", "w1.0",
"还没有", contact,
"Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
controller
@RestController
public class HelloController {
//http://localhost:8081/swagger-ui/index.html
@GetMapping("/hello")
public String Hello() {
return "hello";
}
//只要接口中返回值曾在实体类 就会被扫描到swagger中
@PostMapping("/hello")
public User user() {
return new User();
}
@ApiOperation("梅洛天庭") //给接口加注释 放在方法上
@GetMapping("/hello2")
public String Hello1(@ApiParam("传递的用户名") String username) {
return "hello" + username;
}
@PostMapping("/hello3")
public User post(@ApiParam("传递的用户") User user) {
return user;
}
}
在主启动类添加 @EnableWebMvc
访问 -->localhost:8081/swagger-ui/index.html
里面一些信息是可以自己修改的
修改后
里面有自己写的请求
/hello/user请求
这个请求返回的就是一个对象
Swagger可以充当前后端交流的重要桥梁,方便快捷。很实用。