Swagger 简介
-
最流行的APi框架
-
APi自动生成工具=> Api文档与Api定义同步更新
SpringBoot 集成Swagger
1.新建一个SpringBoot Web 项目
2.导入Swagger的依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
3.配置Swagger
@Configuration
@EnableSwagger2//开启Swagger
public class SwaggerConfig { }
4.测试运行 localhost:8080/swagger-ui.html
配置Swagger
Swagger 的Bean 实例 Docket
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
//配置Swagger apiInfo
private ApiInfo apiInfo (){
Contact contact = new Contact("yang","http:47.111.107.209:8080","1622489328@qq.com");
return new ApiInfo(
"public_c_lass API",
"写代码就完事了",
"1.0",
"http:47.111.107.209:8080",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>()
);
}
}
配置展示:
Swagger 配置扫描接口
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//RequestHandlerSelectors 配置扫描接口的方式
//指定要扫描的包
//basePackage : 指定扫描的包
//any :扫描全部
//none : 不扫描
//withMethodAnnotation : 扫描方法上的注解,参数是一个注解的反射现象
//withClassAnnotation : 扫描类上的注解
.apis(RequestHandlerSelectors.basePackage("com.example.department"))
//paths: 过滤什么路径
// .paths(PathSelectors.ant("/example/**"))
.build();
}
//配置Swagger apiInfo
private ApiInfo apiInfo (){
Contact contact = new Contact("yang","http:47.111.107.209:8080","1622489328@qq.com");
return new ApiInfo(
"public_c_lass API",
"写代码就完事了",
"1.0",
"http:47.111.107.209:8080",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>()
);
}
}
APi文档的分组
.groupName("public_c_lass API")
创建多个Docket 来实现配置多个组
实体类配置
//只要接口中返回值中存在实体类,Swagger就会把该实体类加入
@GetMapping("/user")
public User user(@PathVariable("id") Integer id){
//查询所有部门信息
employeeBaseMapper.deleteById(id);
return new User();
}
@ApiModel("用户实体类")
@Component
@ConfigurationProperties(prefix = "user")
public class User {
@ApiModelProperty("用户Id")
private Integer id;
@ApiModelProperty("用户名")
private String userName;
private String passWord;
private String realName;
}
//只要接口中返回值中存在实体类,Swagger就会把该实体类加入
@ApiOperation("用户控制类")
@GetMapping("/user1")
public User user1(@ApiParam("用户id") @PathVariable("id") Integer id){
//查询所有部门信息
employeeBaseMapper.deleteById(id);
return new User();
}