Swagger
Swagger
Swagger简介
- 号称世界上最流行的API框架
- RestFull API文档在线生成工具=>API文档与API定义同步更新
- 直接运行,在线测试API接口
- 支持多种语言:(Java,pHp...)
在项目中使用Swagger需要Springbox
- swagger 2
- ui
springboot集成Swagger
-
新建一个项目springboot - web项目
-
导入相关依赖
<!-- 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>
-
编写有个Hello工程
-
配置Swagger==>Config
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
}
- 测试运行http://localhost:8080/swagger-ui.html
配置Swagger
Swagger的bean实例Docket;
//配置swagger信息=>apiInfo
private ApiInfo apiInfo(){
//作者信息
Contact DEFAULT_CONTACT = new Contact("俞伟", "www.baidu.com", "1091732333@qq.com");
return new ApiInfo("俞伟的Swagger Api文档",
"good",
"1.0",
"",
DEFAULT_CONTACT,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
Swagger配置扫描接口
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//RequestHandlerSelectors 配置要扫描接口的方式
//basePackage 指定要扫描的包
//any():扫描全部
//none():都不扫描
//withClassAnnotation:扫描类上的注解 注解的反射对象
//withMethodAnnotation:扫描方法上的注解
.apis(RequestHandlerSelectors.basePackage("com.yuwei.swagger.controller"))
//过滤一个路径
.paths(PathSelectors.ant("/yuwei/**"))
.build();
}
配置是否启动swagger
//.enable(false)是否启用swagger
.enable(false)
我只希望我的swagger在生成环境中使用,在发布时候不使用
- 判断是否在生产环境 flag= false
- 注入enable(flag)
//设置要显示的Swagger环境
Profiles profiles = Profiles.of("dev","test");
//获取项目环境:
boolean flag = environment.acceptsProfiles(profiles);
//通过 environment.acceptsProfiles 判断是否处在自己设定的环境当中
配置API文档分组
.groupName("狂神")
如何配置多个组:多个Docket方法
@Bean
public Docket docket1() {
return new Docket(DocumentationType.SWAGGER_2).groupName("group1");
}
@Bean
public Docket docket2() {
return new Docket(DocumentationType.SWAGGER_2).groupName("group2");
}
@Bean
public Docket docket3() {
return new Docket(DocumentationType.SWAGGER_2).groupName("group3");
}

浙公网安备 33010602011771号