1.引入依賴(使用的3.0版本,與2.x的版本有所區別)
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2.編寫swagger配置類
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//創建一個Docket的對象,相當於是swagger的一個實例
@Bean
public Docket docket(){
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo());
}
//配置相關的api信息
private ApiInfo apiInfo(){
Contact contact=new Contact("yzy","https://www.cnblogs.com/shouyaya/","1255014278@qq.com");
return new ApiInfo(
"yzy的swaggerAPI文檔",
"第一個swagger程序",
"1.0",
"urn:tos",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>());
}
}
3.啟動應用!訪問swagger頁面
注意:
- 這次更新,移除了原來默認的swagger頁面路徑:
http://host/context-path/swagger-ui.html
,新增了兩個可訪問路徑:http://host/context-path/swagger-ui/index.html
和http://host/context-path/swagger-ui/
- 通過調整日志級別,還可以看到新版本的swagger文檔接口也有新增,除了以前老版本的文檔接口
/v2/api-docs
之外,還多了一個新版本的/v3/api-docs
接口。
4.配置掃描接口及開關
public Docket docket(){
return new Docket(DocumentationType.OAS_30)
.select()
//RequestHandlerSelectors,配置要掃描接口的方式
//basePackage:指定掃描的包路徑
//any:掃描全部
//none:全部不掃描
//withClassAnnotation:掃描類上的注解,如RestController
//withMethodAnnotation:掃描方法上的注解,如GetMapping
.apis(RequestHandlerSelectors.basePackage("com.yzy.swaggertest.controller"))
//設置對應的路徑才獲取
.paths(PathSelectors.ant("/hello"))
.build()
.apiInfo(apiInfo());
}
5.配置生成環境下開啟swagger,發布時關閉
@Bean
public Docket docket(Environment environment){
//判定springboot的配置文件是否使用dev(開發環境)
Profiles profiles=Profiles.of("dev");
boolean flag=environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.OAS_30)
//只有當springboot配置文件為dev開發環境時,才開啟swaggerAPI文檔功能
.enable(flag)
.select()
.apis(RequestHandlerSelectors.basePackage("com.yzy.swaggertest.controller"))
.paths(PathSelectors.ant("/hello"))
.build()
.apiInfo(apiInfo());
}