重磅:Swagger3.0 官方 starter 誕生了,其它的都可以扔了~
點擊上方 java項目開發(fā) ,選擇 星標(biāo) 公眾號
重磅資訊,干貨,第一時間送達(dá)
作者:飛翔的大白菜
blog.csdn.net/wangzhihao1994/article/details/108408420
資料
swagger 官網(wǎng):swagger.io springfox 官網(wǎng):springfox springfox Github 倉庫:springfox / springfox springfox-demos Github 倉庫:springfox / springfox-demos springfox Maven 倉庫:Home ? io.springfox
swagger介紹
對于 Rest API 來說很重要的一部分內(nèi)容就是文檔,Swagger 為我們提供了一套通過代碼和注解自動生成文檔的方法,這一點對于保證 API 文檔的及時性將有很大的幫助。
Swagger 是一套基于 OpenAPI 規(guī)范(OpenAPI Specification,OAS)構(gòu)建的開源工具,可以幫助我們設(shè)計、構(gòu)建、記錄以及使用 Rest API。
OAS本身是一個API規(guī)范,它用于描述一整套API接口,包括一個接口是哪種請求方式、哪些參數(shù)、哪些header等,都會被包括在這個文件中。它在設(shè)計的時候通常是YAML格式,這種格式書寫起來比較方便,而在網(wǎng)絡(luò)中傳輸時又會以json形式居多,因為json的通用性比較強。
Swagger 主要包含了以下三個部分:
Swagger Editor:基于瀏覽器的編輯器,我們可以使用它編寫我們 OpenAPI 規(guī)范。 Swagger UI:它會將我們編寫的 OpenAPI 規(guī)范呈現(xiàn)為交互式的 API 文檔,后文我將使用瀏覽器來查看并且操作我們的 Rest API。 Swagger Codegen:它可以通過為 OpenAPI(以前稱為 Swagger)規(guī)范定義的任何 API 生成服務(wù)器存根和客戶端 SDK 來簡化構(gòu)建過程。
springfox介紹
由于Spring的流行,Marty Pitt編寫了一個基于Spring的組件swagger-springmvc,用于將swagger集成到springmvc中來,而springfox則是從這個組件發(fā)展而來。
通常SpringBoot項目整合swagger需要用到兩個依賴:springfox-swagger2和springfox-swagger-ui,用于自動生成swagger文檔。
springfox-swagger2:這個組件的功能用于幫助我們自動生成描述API的json文件 springfox-swagger-ui:就是將描述API的json文件解析出來,用一種更友好的方式呈現(xiàn)出來。
SpringFox 3.0.0 發(fā)布
官方說明:
SpringFox 3.0.0 發(fā)布了,SpringFox 的前身是 swagger-springmvc,是一個開源的 API doc 框架,可以將 Controller 的方法以文檔的形式展現(xiàn)。 首先,非常感謝社區(qū)讓我有動力參與這個項目。在這個版本中,在代碼、注釋、bug報告方面有一些非常驚人的貢獻(xiàn),看到人們在問題論壇上跳槽來解決問題,我感到很謙卑。它確實激勵我克服“困難”,開始認(rèn)真地工作。有什么更好的辦法來擺脫科維德的憂郁! 注意:這是一個突破性的變更版本,我們已經(jīng)盡可能地保持與springfox早期版本的向后兼容性。在2.9之前被棄用的api已經(jīng)被積極地刪除,并且標(biāo)記了將在不久的將來消失的新api。所以請注意這些,并報告任何遺漏的內(nèi)容。
新特性:
Remove explicit dependencies on springfox-swagger2 Remove any @EnableSwagger2… annotations Add the springfox-boot-starter dependency Springfox 3.x removes dependencies on guava and other 3rd party libraries (not zero dep yet! depends on spring plugin and open api libraries for annotations and models) so if you used guava predicates/functions those will need to transition to java 8 function interfaces.
此版本的亮點:
Spring5,Webflux支持(僅支持請求映射,尚不支持功能端點)。 Spring Integration支持(非常感謝反饋)。 SpringBoot支持 springfox Boot starter依賴性(零配置、自動配置支持)。具有自動完成功能的文檔化配置屬性。 更好的規(guī)范兼容性與2.0。 支持OpenApi 3.0.3。 零依賴。幾乎只需要spring-plugin,swagger-core ,現(xiàn)有的swagger2注釋將繼續(xù)工作并豐富openapi3.0規(guī)范。
兼容性說明:
需要Java 8 需要Spring5.x(未在早期版本中測試) 需要SpringBoot 2.2+(未在早期版本中測試)
注意:
應(yīng)用主類增加注解@EnableOpenApi,刪除之前版本的SwaggerConfig.java。
啟動項目,訪問地址:http://localhost:8080/swagger-ui/index.html,注意2.x版本中訪問的地址的為http://localhost:8080/swagger-ui.html
整合使用
Maven項目中引入springfox-boot-starter依賴:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
12345
application.yml配置
spring:
application:
name: springfox-swagger
server:
port: 8080
# ===== 自定義swagger配置 ===== #
swagger:
enable: true
application-name: ${spring.application.name}
application-version: 1.0
application-description: springfox swagger 3.0整合Demo
try-host: http://localhost:${server.port}
12345678910111213
使用@EnableOpenApi注解,啟用swagger配置
@EnableOpenApi
@Configuration
public class SwaggerConfiguration {
}
12345
自定義swagger配置類SwaggerProperties
@Component
@ConfigurationProperties("swagger")
public class SwaggerProperties {
/**
* 是否開啟swagger,生產(chǎn)環(huán)境一般關(guān)閉,所以這里定義一個變量
*/
private Boolean enable;
/**
* 項目應(yīng)用名
*/
private String applicationName;
/**
* 項目版本信息
*/
private String applicationVersion;
/**
* 項目描述信息
*/
private String applicationDescription;
/**
* 接口調(diào)試地址
*/
private String tryHost;
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public String getApplicationVersion() {
return applicationVersion;
}
public void setApplicationVersion(String applicationVersion) {
this.applicationVersion = applicationVersion;
}
public String getApplicationDescription() {
return applicationDescription;
}
public void setApplicationDescription(String applicationDescription) {
this.applicationDescription = applicationDescription;
}
public String getTryHost() {
return tryHost;
}
public void setTryHost(String tryHost) {
this.tryHost = tryHost;
}
}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
一個完整詳細(xì)的springfox swagger配置示例:
import io.swagger.models.auth.In;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.boot.SpringBootVersion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.lang.reflect.Field;
import java.util.*;
@EnableOpenApi
@Configuration
public class SwaggerConfiguration implements WebMvcConfigurer {
private final SwaggerProperties swaggerProperties;
public SwaggerConfiguration(SwaggerProperties swaggerProperties) {
this.swaggerProperties = swaggerProperties;
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30).pathMapping("/")
// 定義是否開啟swagger,false為關(guān)閉,可以通過變量控制
.enable(swaggerProperties.getEnable())
// 將api的元信息設(shè)置為包含在json ResourceListing響應(yīng)中。
.apiInfo(apiInfo())
// 接口調(diào)試地址
.host(swaggerProperties.getTryHost())
// 選擇哪些接口作為swagger的doc發(fā)布
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
// 支持的通訊協(xié)議集合
.protocols(newHashSet("https", "http"))
// 授權(quán)信息設(shè)置,必要的header token等認(rèn)證信息
.securitySchemes(securitySchemes())
// 授權(quán)信息全局應(yīng)用
.securityContexts(securityContexts());
}
/**
* API 頁面上半部分展示信息
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title(swaggerProperties.getApplicationName() + " Api Doc")
.description(swaggerProperties.getApplicationDescription())
.contact(new Contact("lighter", null, "[email protected]"))
.version("Application Version: " + swaggerProperties.getApplicationVersion() + ", Spring Boot Version: " + SpringBootVersion.getVersion())
.build();
}
/**
* 設(shè)置授權(quán)信息
*/
private List<SecurityScheme> securitySchemes() {
ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());
return Collections.singletonList(apiKey);
}
/**
* 授權(quán)信息全局應(yīng)用
*/
private List<SecurityContext> securityContexts() {
return Collections.singletonList(
SecurityContext.builder()
.securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{new AuthorizationScope("global", "")})))
.build()
);
}
@SafeVarargs
private final <T> Set<T> newHashSet(T... ts) {
if (ts.length > 0) {
return new LinkedHashSet<>(Arrays.asList(ts));
}
return null;
}
/**
* 通用攔截器排除swagger設(shè)置,所有攔截器都會自動加swagger相關(guān)的資源排除信息
*/
@SuppressWarnings("unchecked")
@Override
public void addInterceptors(InterceptorRegistry registry) {
try {
Field registrationsField = FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
List<InterceptorRegistration> registrations = (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);
if (registrations != null) {
for (InterceptorRegistration interceptorRegistration : registrations) {
interceptorRegistration
.excludePathPatterns("/swagger**/**")
.excludePathPatterns("/webjars/**")
.excludePathPatterns("/v3/**")
.excludePathPatterns("/doc.html");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
一些常用注解說明
@Api:用在controller類,描述API接口 @ApiOperation:描述接口方法 @ApiModel:描述對象 @ApiModelProperty:描述對象屬性 @ApiImplicitParams:描述接口參數(shù) @ApiResponses:描述接口響應(yīng) @ApiIgnore:忽略接口方法
示例
項目Demo:springfox-swagger
效果圖:
example
參考
在 Spring Boot 項目中使用 Swagger 文檔 Springfox 3.0.0(包含springfox-swagger2-3.0.0)即OpenAPI 3的發(fā)布與系統(tǒng)集成
--完--推薦閱讀:
怎么接私貨?這個渠道你100%有用!請收藏!喜歡文章,點個在看

