Swagger:一个用于即时前后端联调的框架
- Api文档与API同步更新。
- 直接运行,可以在线测试API接口。
- 支持多种语言
一,使用Swagger需要springfox
- swagger2
- ui
二,Spring Boot集成Swagger2.x
1,导入依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
2,配置Swagger
@Configuration
@EnableSwagger2
3,访问页
http://localhost:8080/swagger-ui.html
三,Spring Boot集成Swagger3.x
1,导入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2,配置Swagger
@Configuration
@EnableOpenApi(可以省略)
3,访问页
http://localhost:8080/swagger-ui/index.html
四,配置Swagger
1,Swagger的bean实例Docket;
private ApiInfo apiInfo(){
Contact contact=new Contact("宇宙伟","https://www.baidu.com/","2117008741@qq.com");
return new ApiInfo("宇宙伟的SWAGGER"
, "知行合一"
, "1.0"
, "hut"
, contact
, "Apache 2.0"
, "http://www.apache.org/licenses/LICENSE-2.0"
,new ArrayList<>());
}
2,Swagger配置扫描接口
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//RequestHandlerSelectors配置要扫描接口的方式
.apis(RequestHandlerSelectors.basePackage("com.wei.swagger.controller"))
//paths过滤什么路径
//.paths(PathSelectors.ant("/wei/**"))
.build();
}
3,多环境切换
Profiles profile = Profiles.of("dev", "test");
Boolean flag = environment.acceptsProfiles(profile);
.enable(flag) //开关Swagger
4,配置API文档分组
.groupName("cosmos")
5,配置多组
@Bean
public Docket docket1() {
return new Docket(DocumentationType.SWAGGER_2).groupName("wei");
}
@Bean
public Docket docket2() {
return new Docket(DocumentationType.SWAGGER_2).groupName("huang");
}
@Bean
public Docket docket3() {
return new Docket(DocumentationType.SWAGGER_2).groupName("xu");
}
6,配置实体类
package com.wei.swagger.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel("用户实体类") //注释作用
public class User {
@ApiModelProperty("用户名")
public String username;
@ApiModelProperty("用户名")
private String password;
}
@PostMapping("/user")
public User user(){
return new User();
}
@ApiOperation("hello控制类")
@GetMapping("/hello")
public String hello() {
return "hello";
}
注意点:
- 如果没有set,get方法(@Data,@AllArgsConstructor,@NoArgsConstructor),实体类的属性用public才能在Swagger找到
- @ApiXXX注释是用来给属性注释
五,总结
- 我们可以通过swagger给一些比较难以理解的属性或者接口增加注释信息
- 接口文档实更新
- 可以在线测试
注意点:
在正式发布时,要关闭Swagger,安全与效率问题。