Java項目中使用Swagger功能

一,Swagger功能是什麼呢?

簡單說就是生產API接口文檔,同時提供在線調試項目API的接口的功能,可以說對推進項目進度非常有利,尤其對前後臺分離的情況更加有用;

二,如何在Java項目中使用Swagger功能,歡迎使用推薦的方式

1,過去的Swagger使用方式【不推薦使用】

(1)引入依賴 jar 包,如下:

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version> 
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version> 
</dependency>

(2)配置Swagger2Config.java


package com.qyh.pro01.config;

import java.io.Serializable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


/**
 * Swagger配置類
 * @author shenzhenNBA
 * @since 2020.02.16
 */

@Configuration
@EnableSwagger2 
public class Swagger2Config implements Serializable {

	private static final long serialVersionUID = 202002161810010L;
	
	@Bean
	public Docket api() {
		return new Docket(DocumentationType.SWAGGER_2)
			.apiInfo(apiInfo())
			.select()
			.apis(RequestHandlerSelectors.basePackage("com.xxx.yyy.controller"))
			.apis(Swagger2Config.basePackage("com.xxx.yyy.controller"))
			.paths(PathSelectors.any())
			.build();			
	}
	
	
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("Swagger2-api文檔")
				.description("Swagger2接口教程")
				.termsOfServiceUrl("http://www.baidu.com")
				.version("1.0.0")
				.contact(new Contact("shenzhenNBA", 
						"http://www.xxx.com", 
						"[email protected]"))
				.build();
	}
		
}

還有些可能需要springMVC配置文件排除放行Swagger相關的html,css,JS和圖片(jpg,png,gif等),然後在項目使用,例如:http://localhost:8080/swagger-ui.html

2,Springdoc方式使用Swagger功能【推薦使用】

過去的方式也許還是有點繁瑣,是時候換Springdoc方式使用Swagger功能了,當然這個也是基於Swagger2.x實現,它完美支持SpringBoot 1.x/2.x,Swagger-ui也比較好看,其它次要的暫時忽略;然後在項目中增加依賴 jar 包,

<dependency>
	<groupId>org.springdoc</groupId>
	<artifactId>springdoc-openapi-ui</artifactId>
	<version>1.2.30</version> 
	<!-- 版本可自行選擇最新版本-->
</dependency

在下載這些 JAR包時,如果是從國外官方的可能耗時間比較久,可以修改maven倉庫的配置文件,修改如下:

<!-- 阿里的公開maven庫,在 mirrors標籤的內部追(增)加如下內容 -->
<mirrors>

	<mirror>  
	   <id>alimaven</id>  
	   <name>aliyun maven</name>  
	   <url>http://maven.aliyun.com/nexus/content/groups/public/</url>  
	   <mirrorOf>central</mirrorOf>          
	</mirror>
</mirrors>

從國內的ali的鏡像倉庫中下載,速度要快蠻多;記住,然後什麼都不用做了,啓動項目,直接可根據項目訪問Swagger功能了,訪問URL格式:http://ip:port/swagger-ui.html

例如我的:http://127.0.0.1/swagger-ui.html 很直觀看到API接口,同時通過 “try it out” 可直接在線調試了,非常方便快速... 看看一下部分截圖:









 

三,後記,

basic-error-controller 這些API是自動生成的,可以不理,僅關注自己開發的API接口即可,總之,使用springdoc這種方式使用swagger功能,非常方便,簡單,快速,可以快速查看項目各個API文檔,同時非常方便在線調試,尤其是對前後端分離的項目更加有利推進項目進度,可能有些考慮不周,歡迎拍磚...

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章