Swagger
- 世界上最流行的Api框架;
- RestFul Api文档在线自动生成工具=>Api文档与Api定义同步更新;
- 直接运行,在线测试Api接口;
- 支持多种语言:(java,php)
1.依赖
使用Swagger需要springbox:
<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>
2.Swagger的使用
1)编写hello工程
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello";
}
}
2)配置swagger
@Configuration
@EnableSwagger2
public class SwaggerConfig {
}
3) 测试运行,访问localhost:8080/swagger-ui.html
3.编辑配置
配置Swagger信息
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
Contact contact=new Contact("mingiao","https://blog.csdn.net/mingiao","12345678@qq.com");
return new ApiInfo(
"mingiao的Swagger Api文档",
"所有的不期而遇都是生活给你的惊喜",
"1.0",
"urn:tos",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/License-2.0",
new ArrayList()
);
}
}
测试结果:
配置扫描接口
Docket.select()
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.mingiao.demo.controller"))
.build();
}
测试结果:
配置是否启动Swagger
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.mingiao.demo.controller"))
.build();
}
测试结果:
配置Api的分组
.groupName("mingiao")
测试结果:
配置多个分组
创建多个Docket实例
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2).groupName("C");
}
测试结果:
4.接口的测试与使用
给实体类添加注释
@ApiModel("用户实体类")
public class User {
@ApiModelProperty("用户名")
public String username;
@ApiModelProperty("密码" )
public String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- @ApiModel:给类添加注释
- @ApiModelProperty:给类中的字段添加注释
效果:
给接口添加注释
@GetMapping("/hello1")
@ApiOperation("Hello控制类")
public String hello1(@ApiParam("用户名") String username){
return "hello"+username;
}
- @ApiOperation(): 给api请求添加注释
- @ApiParam():给参数添加注释
效果:
接口测试
@PostMapping("/postt")
@ApiOperation("post控制类")
public User postt(@ApiParam("用户名") User user){
return user;
}
? 1.点开测试的接口
? 2.点击Try it out进入测试
3.填入相关属性(字段),点击Execute提交
4.观察运行结果,若成功为200,失败为500
|