一:swagger是什么?
1、是一款讓你更好的書寫API文檔的規范且完整框架。
2、提供描述、生產、消費和可視化RESTful Web Service。
3、是由龐大工具集合支撐的形式化規范。這個集合涵蓋了從終端用戶接口、底層代碼庫到商業API管理的方方面面。
方法一:使用第三方依賴(最簡單的方法)
1、在pom.xml文件中添加第三方swagger依賴()

<dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.7.0.RELEASE</version> </dependency>
2、在Spring Boot項目的啟動類上添加@EnableSwagger2Doc注解,就可以直接使用啦。
3、https://github.com/SpringForAll/spring-boot-starter-swagger這是GitHub上這個swagger依賴實現的項目,里面有詳細的講解。
方法二:使用官方依賴
1、在pom.xml文件中添加swagger相關依賴

<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox-version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox-version}</version> </dependency>
第一個是API獲取的包,第二是官方給出的一個ui界面。這個界面可以自定義,默認是官方的,對於安全問題,以及ui路由設置需要着重思考。
2、swagger的configuration
需要特別注意的是swagger scan base package,這是掃描注解的配置,即你的API接口位置。

@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.yss.ms.admin"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("服務:發布為daocke鏡像,權限管理,用戶管理,頁面管理,日志 后台 APIs")
.description("服務:發布為daocke鏡像,權限管理,用戶管理,頁面管理,日志 后台")
.termsOfServiceUrl("http://192.168.103.198:10070/platformgroup/ms-admin")
.contact("程序猿DD")
.version("1.0")
.build();
}
}
三、具體使用
1、在API上做一些聲明

@RequestMapping("/swagger/test/map") @ApiOperation(value="xxxx", tags = "xxxx") @ApiImplicitParams({ @ApiImplicitParam(name="name", dataType = "string", value = "only return models...") }) @ApiResponses(value = { @ApiResponse(code = 200, message="Indicates ..."), @ApiResponse(code = 404, message = "not found error") }) public Result<String> testSwaggerMap(Map map){ return null; }
https://blog.csdn.net/xtj332/article/details/80595768
如果項目文檔訪問出現404,參照上面的地址查看原因
https://www.cnblogs.com/mingxiaoyue/p/8877429.html
如果樣式出現問題請參考上面查看原因
我在實踐中遇到只有swagger頁面頭部的情況,沒有一個api顯示,經過查證之后發現是shiro安全框架攔截了,將其注釋掉之后就好了。具體原因還沒有確定,等待有時間查一下,又或許沒法解決,反正上線的時候可以將enable改為false,然后開啟shiro等安全框架的攔截。