Swagger自動介面文件生成框架————springboot整合swagger總結
阿新 • • 發佈:2018-12-24
swagger簡介:
swagger是一款開源的api介面文件生成工具。
Swagger的專案主頁:https://swagger.io/ 目前比較流行的做法是在程式碼中加入swagger相關的註釋,然後,利用小工具生成swagger.json或者swagger.yaml檔案。
springboot將swagger變得更加簡單:
springboot擁有自己的自動配置特性,而swagger也釋出了應用於springboot的自動依賴配置模組。
也就是說,只需要在pom檔案中引入swagger模組配置資訊,然後在application中進行swagger框架的簡單配置,即可輕鬆通過瀏覽器訪問由swagger為我們生成的網頁版介面說明文件。
具體步驟:
1.首先我們需要在pom.xml中加入swagger模組配置資訊,將swagger模組引入到專案中:
<!-- https://mvnrepository.com/artifact/com.spring4all/spring-boot-starter-swagger --> <dependency> <groupId>com.spring4all</groupId> <artifactId>spring-boot-starter-swagger</artifactId> <version>1.5.1.RELEASE</version> </dependency>
2.在springboot啟動類中加入註解:
@EnableSwagger2Doc
@SpringBootApplication
public class Bootstrap {
public static void main(String[] args) {
SpringApplication.run(Bootstrap.class, args);
}
}
3.加入swagger配置資訊:
在網上看到有兩種配置方式,一種是另起一個application.yaml,然後通過yaml語言進行配置,另一種方式是在已有的application.properties中加入配置(這裡記載第二種方式):
#swagger配置資訊
swagger.title=yyh project online API specification
swagger.description=the web page which you opened is generated by swagger automatically
swagger.version=1.5.0.RELEASE
swagger.license=Apache License, Version 2.0
swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html
swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger
swagger.contact.name=mht
swagger.contact.url=http://localhost:8080/swagger-ui.html
[email protected]
swagger.base-package=com.seco
swagger.base-path=/**
#配置說明:
swagger.title=標題
swagger.description=描述
swagger.version=版本
swagger.license=許可證
swagger.licenseUrl=許可證URL
swagger.termsOfServiceUrl=服務條款URL
swagger.contact.name=維護人
swagger.contact.url=維護人URL
swagger.contact.email=維護人email
swagger.base-package=swagger掃描的基礎包,預設:全掃描
swagger.base-path=需要處理的基礎URL規則,預設:/**
swagger.exclude-path=需要排除的URL規則,預設:空
4.API文件效果檢視:
啟動專案,開啟瀏覽器在位址列輸入如下地址即可檢視生成的API文件:
http://localhost:8080/swagger-ui.html
參考文章:
==============================2018-8-8 ,星期三,下午,更新 ==============================
Spring Boot+shiro攔截swagger路徑問題解決
在shiro攔截器配置方法中,加入對swagger的開發路徑即可,如下程式碼所示
/**
* 配置shiro攔截器,用於url,粗粒度攔截
* <br>作者: mht<br>
* 時間:2018年8月3日-上午10:29:07<br>
* @return
*/
@Bean
public ShiroFilterChainDefinition chain() {
DefaultShiroFilterChainDefinition chain = new DefaultShiroFilterChainDefinition();
chain.addPathDefinition("/users/login", "anon");
// 除了以上url剩下的都需要登入 TODO:攔截後的跳轉功能
//swagger介面許可權 開放4個路徑
chain.addPathDefinition("/swagger-ui.html", "anon");
chain.addPathDefinition("/webjars/**", "anon");
chain.addPathDefinition("/v2/**", "anon");
chain.addPathDefinition("/swagger-resources/**", "anon");
chain.addPathDefinition("/**", "authc");
return chain;
}
注:其中,/webjars/** 和 /v2/** 也是swagger 的相關資源路徑,需要一同開放。