SpringBoot集成Swagger
一、集成Swagger
1、新建一个springboot的web项目
2、导入相关依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
3、编写一个hello工程
4、配置Swagger==>Config
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
}
5、测试运行:http://localhost:8080/swagger-ui.html
二、配置Swagger
Swagger的bean实例 Docket;
三、Swagger配置扫描接口
Docket.select();
//配置了Swagger的Docket的bean实例
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//RequestHandlerSelectors 配置要扫描接口的方式
//basepackage 指定要扫描的包
//any() 扫描全部
//none() 不扫描
.apis(RequestHandlerSelectors.basePackage("cn.nongyanxia.controller"))
//过滤什么路径
//只扫描/gump下的,所以启动之后便没有了
.paths(PathSelectors.ant("/gump/**"))
.build();
}
配置是否启动Swagger
enable() 参数为布尔类型 true为启动 false关闭
问题:我只希望我的Swagger在生产环境中使用,在发布的时候不使用。
1、判断是不是生产环境 flag=false
2、注入enable
四、配置API文档的分组
问题:如何配置多个组
配置多个Docket实例即可。
五、实体类配置
1、实体类
//文档注释
@ApiModel("用户实体类")
public class User {
@ApiModelProperty("用户名")
public String username;
@ApiModelProperty("用户密码")
public String password;
}
2、控制层
//只要我们的接口中,返回值中存在实体类,它就会被扫描到Swagger中
@PostMapping("/user")
public User user(){
return new User();
}
结果:
总结:
1、我们可以通过Swagger对一些比较难以理解的属性或者接口,增加注释信息。
2、接口文档实时更新
3、可以在线测试
Swagger是一个优秀的工具,几乎所有大公司都有使用它
【注意点】在正式发布的时候,出于安全考虑和节省内存,要关闭掉Swagger
Q.E.D.