<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Swagger 3.0 官方 starter 誕生了,其它的都可以扔了~

          共 8759字,需瀏覽 18分鐘

           ·

          2020-10-19 22:04

          注意文末有最新Java實戰(zhàn)項目面試題



          # swagger介紹


          對于 Rest API 來說很重要的一部分內容就是文檔,Swagger 為我們提供了一套通過代碼和注解自動生成文檔的方法,這一點對于保證 API 文檔的及時性將有很大的幫助。


          Swagger 是一套基于 OpenAPI 規(guī)范(OpenAPI Specification,OAS)構建的開源工具,可以幫助我們設計、構建、記錄以及使用 Rest API。


          OAS本身是一個API規(guī)范,它用于描述一整套API接口,包括一個接口是哪種請求方式、哪些參數、哪些header等,都會被包括在這個文件中。它在設計的時候通常是YAML格式,這種格式書寫起來比較方便,而在網絡中傳輸時又會以json形式居多,因為json的通用性比較強。


          Swagger 主要包含了以下三個部分:


          • Swagger Editor:基于瀏覽器的編輯器,我們可以使用它編寫我們 OpenAPI 規(guī)范。


          • Swagger UI:它會將我們編寫的 OpenAPI 規(guī)范呈現為交互式的 API 文檔,后文我將使用瀏覽器來查看并且操作我們的 Rest API。


          • Swagger Codegen:它可以通過為 OpenAPI(以前稱為 Swagger)規(guī)范定義的任何 API 生成服務器存根和客戶端 SDK 來簡化構建過程。


          # 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文件解析出來,用一種更友好的方式呈現出來。


          # SpringFox 3.0.0 發(fā)布


          官方說明:


          • SpringFox 3.0.0 發(fā)布了,SpringFox 的前身是 swagger-springmvc,是一個開源的 API doc 框架,可以將 Controller 的方法以文檔的形式展現。




          新特性:


          • 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?,現有的swagger2注釋將繼續(xù)工作并豐富openapi3.0規(guī)范。


          兼容性說明:


          • 需要Java 8


          • 需要Spring5.x(未在早期版本中測試)


          • 需要SpringBoot 2.2+(未在早期版本中測試)


          注意:


          應用主類增加注解@EnableOpenApi,刪除之前版本的SwaggerConfig.java。


          啟動項目,訪問地址:http://localhost:8080/swagger-ui/index.html,注意2.x版本中訪問的地址的為http://localhost:8080/swagger-ui.html


          # 整合使用


          Maven項目中引入springfox-boot-starter依賴:

              io.springfox    springfox-boot-starter    3.0.0

          application.yml配置

          spring:  application:    name: springfox-swaggerserver:  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}

          使用@EnableOpenApi注解,啟用swagger配置

          @EnableOpenApi@Configurationpublic class SwaggerConfiguration {
          }

          自定義swagger配置類SwaggerProperties

          @Component@ConfigurationProperties("swagger")public class SwaggerProperties {    /**     * 是否開啟swagger,生產環(huán)境一般關閉,所以這里定義一個變量     */    private Boolean enable;
          /** * 項目應用名 */ private String applicationName;
          /** * 項目版本信息 */ private String applicationVersion;
          /** * 項目描述信息 */ private String applicationDescription;
          /** * 接口調試地址 */ 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;????}
          • ?

          一個完整詳細的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@Configurationpublic 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為關閉,可以通過變量控制 .enable(swaggerProperties.getEnable())
          // 將api的元信息設置為包含在json ResourceListing響應中。 .apiInfo(apiInfo())
          // 接口調試地址 .host(swaggerProperties.getTryHost())
          // 選擇哪些接口作為swagger的doc發(fā)布 .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build()
          // 支持的通訊協(xié)議集合 .protocols(newHashSet("https", "http"))
          // 授權信息設置,必要的header token等認證信息 .securitySchemes(securitySchemes())
          // 授權信息全局應用 .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(); }
          /** * 設置授權信息 */ private List securitySchemes() { ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue()); return Collections.singletonList(apiKey); }
          /** * 授權信息全局應用 */ private List securityContexts() { return Collections.singletonList( SecurityContext.builder() .securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{new AuthorizationScope("global", "")}))) .build() ); }
          @SafeVarargs private final Set newHashSet(T... ts) { if (ts.length > 0) { return new LinkedHashSet<>(Arrays.asList(ts)); } return null; }
          /** * 通用攔截器排除swagger設置,所有攔截器都會自動加swagger相關的資源排除信息 */ @SuppressWarnings("unchecked") @Override public void addInterceptors(InterceptorRegistry registry) { try { Field registrationsField = FieldUtils.getField(InterceptorRegistry.class, "registrations", true); List registrations = (List) 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(); } }
          }

          # 一些常用注解說明


          • @Api:用在controller類,描述API接口

          • @ApiOperation:描述接口方法

          • @ApiModel:描述對象

          • @ApiModelProperty:描述對象屬性

          • @ApiImplicitParams:描述接口參數

          • @ApiResponses:描述接口響應

          • @ApiIgnore:忽略接口方法


          效果圖:

          # 資料


          • swagger 官網:https://swagger.io

          • springfox 官網:http://springfox.github.io

          • springfox Github 倉庫:springfox / springfox

          • springfox-demos Github 倉庫:https://github.com/springfox/springfox

          來源:https://blog.csdn.net/wangzhihao1994/article/details/108408420


          ---END---
          文末福利



          瀏覽 43
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  无码无套少妇毛多18PXXXX | 嫩草97| 日曰日天天日 | 成人一区视频 | 91无码人妻精品1国产动漫 |