导入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
访问:http://localhost:8080/swagger-ui/index.html 就可以实现swagger-ui.html的访问
定制swagger
编写swagger配置类
因为实际开发中有多种环境 所以在上线后要关闭swagger
在配置文件中激活开发环境
#激活开发环境
spring.profiles.active=dev
在docket中配置
Profiles profiles=Profiles.of("dev","test");
boolean flag = environment.acceptsProfiles(profiles);
.enable(flag)
代表只有这两个环境能激活swagger
可自定义界面的文档信息(没什么用)
//配置swagger文档信息apiInfo
private ApiInfo apiInfo(){
Contact contact = new Contact("zwy", "https:/www.baidu.com", "928451384@qq.com");
return new ApiInfo(
"zwy1111111",
"今天心情不好",
"1.0",
"urn:tos",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
整体swagger的配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
//一个docket的bean代表一个swagger 相当于一个管理员
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 docket(Environment environment){
//配置了swagger的bean实例
//获取项目的环境 是发布 还是测试
//设置要显示swagger的环境 在有些环境下并不希望swagger激活
Profiles profiles=Profiles.of("dev","test");
//看换经是不是这些环境
//在把得到的flag 作为标记是否激活swagger
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//是否启用swagger
.enable(flag)
//分组 一个组对应一个docket
.groupName("zwy")
.select()
//apis:扫描指定包的controller
.apis(RequestHandlerSelectors.basePackage("com.zhou.springboot12swagger.controller"))
//paths()过滤什么路径 只扫秒/zhou下面的api
// .paths(PathSelectors.ant("/zhou/**"))
.build();
}
//配置swagger文档信息apiInfo
private ApiInfo apiInfo(){
Contact contact = new Contact("zwy", "https:/www.baidu.com", "928451384@qq.com");
return new ApiInfo(
"zwy1111111",
"今天心情不好",
"1.0",
"urn:tos",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
}
多个docket可实现多个分组
一些常用标记
/可用来标记用户实体
@ApiModel("用户实体类")
public class User {
//给整个controller加注释
@Api(tags = "hahahjahahhahahaha")
public class MyController {
//给接口加注释
@ApiOperation("CONTROLLER11111111111111111111")
@GetMapping("/hello")
public String hello(){
return "hello";
}
总结:swagger的作用
1:可以给一些属性 接口进行注释 增加代码的可读性
2:接口相关的文档可以在线更新
3:可以在线测试接口