<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>

          重磅:Swagger3.0 官方 starter 誕生了,其它的都可以扔了~

          共 16765字,需瀏覽 34分鐘

           ·

          2021-04-03 23:17

          點(diǎn)擊上方 好好學(xué)java ,選擇 星標(biāo) 公眾號(hào)

          重磅資訊,干貨,第一時(shí)間送達(dá)

          今日推薦:推薦 19 個(gè) github 超牛逼項(xiàng)目!

          個(gè)人原創(chuàng)100W +訪問(wèn)量博客:點(diǎn)擊前往,查看更多

          作者:飛翔的大白菜

          blog.csdn.net/wangzhihao1994/article/details/108408420

          資料

          • swagger 官網(wǎng):swagger.io
          • springfox 官網(wǎng):springfox
          • springfox Github 倉(cāng)庫(kù):springfox / springfox
          • springfox-demos Github 倉(cāng)庫(kù):springfox / springfox-demos
          • springfox Maven 倉(cāng)庫(kù):Home ? io.springfox

          swagger介紹

          對(duì)于 Rest API 來(lái)說(shuō)很重要的一部分內(nèi)容就是文檔,Swagger 為我們提供了一套通過(guò)代碼和注解自動(dòng)生成文檔的方法,這一點(diǎn)對(duì)于保證 API 文檔的及時(shí)性將有很大的幫助。

          Swagger 是一套基于 OpenAPI 規(guī)范(OpenAPI Specification,OAS)構(gòu)建的開源工具,可以幫助我們?cè)O(shè)計(jì)、構(gòu)建、記錄以及使用 Rest API。

          OAS本身是一個(gè)API規(guī)范,它用于描述一整套API接口,包括一個(gè)接口是哪種請(qǐng)求方式、哪些參數(shù)、哪些header等,都會(huì)被包括在這個(gè)文件中。它在設(shè)計(jì)的時(shí)候通常是YAML格式,這種格式書寫起來(lái)比較方便,而在網(wǎng)絡(luò)中傳輸時(shí)又會(huì)以json形式居多,因?yàn)閖son的通用性比較強(qiáng)。

          Swagger 主要包含了以下三個(gè)部分:

          • Swagger Editor:基于瀏覽器的編輯器,我們可以使用它編寫我們 OpenAPI 規(guī)范。
          • Swagger UI:它會(huì)將我們編寫的 OpenAPI 規(guī)范呈現(xiàn)為交互式的 API 文檔,后文我將使用瀏覽器來(lái)查看并且操作我們的 Rest API。
          • Swagger Codegen:它可以通過(guò)為 OpenAPI(以前稱為 Swagger)規(guī)范定義的任何 API 生成服務(wù)器存根和客戶端 SDK 來(lái)簡(jiǎn)化構(gòu)建過(guò)程。

          springfox介紹

          由于Spring的流行,Marty Pitt編寫了一個(gè)基于Spring的組件swagger-springmvc,用于將swagger集成到springmvc中來(lái),而springfox則是從這個(gè)組件發(fā)展而來(lái)。

          通常SpringBoot項(xiàng)目整合swagger需要用到兩個(gè)依賴:springfox-swagger2springfox-swagger-ui,用于自動(dòng)生成swagger文檔。

          • springfox-swagger2:這個(gè)組件的功能用于幫助我們自動(dòng)生成描述API的json文件
          • springfox-swagger-ui:就是將描述API的json文件解析出來(lái),用一種更友好的方式呈現(xiàn)出來(lái)。

          SpringFox 3.0.0 發(fā)布

          官方說(shuō)明:

          • SpringFox 3.0.0 發(fā)布了,SpringFox 的前身是 swagger-springmvc,是一個(gè)開源的 API doc 框架,可以將 Controller 的方法以文檔的形式展現(xiàn)。
          • 首先,非常感謝社區(qū)讓我有動(dòng)力參與這個(gè)項(xiàng)目。在這個(gè)版本中,在代碼、注釋、bug報(bào)告方面有一些非常驚人的貢獻(xiàn),看到人們?cè)趩?wèn)題論壇上跳槽來(lái)解決問(wèn)題,我感到很謙卑。它確實(shí)激勵(lì)我克服“困難”,開始認(rèn)真地工作。有什么更好的辦法來(lái)擺脫科維德的憂郁!
          • 注意:這是一個(gè)突破性的變更版本,我們已經(jīng)盡可能地保持與springfox早期版本的向后兼容性。在2.9之前被棄用的api已經(jīng)被積極地刪除,并且標(biāo)記了將在不久的將來(lái)消失的新api。所以請(qǐng)注意這些,并報(bào)告任何遺漏的內(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.

          此版本的亮點(diǎn):

          • Spring5,Webflux支持(僅支持請(qǐng)求映射,尚不支持功能端點(diǎn))。
          • Spring Integration支持(非常感謝反饋)。
          • SpringBoot支持springfox Boot starter依賴性(零配置、自動(dòng)配置支持)。
          • 具有自動(dòng)完成功能的文檔化配置屬性。
          • 更好的規(guī)范兼容性與2.0。
          • 支持OpenApi 3.0.3。
          • 零依賴。幾乎只需要spring-plugin,swagger-core ,現(xiàn)有的swagger2注釋將繼續(xù)工作并豐富openapi3.0規(guī)范。

          兼容性說(shuō)明:

          • 需要Java 8
          • 需要Spring5.x(未在早期版本中測(cè)試)
          • 需要SpringBoot 2.2+(未在早期版本中測(cè)試)

          注意:

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

          啟動(dòng)項(xiàng)目,訪問(wèn)地址:http://localhost:8080/swagger-ui/index.html,注意2.x版本中訪問(wèn)的地址的為http://localhost:8080/swagger-ui.html

          整合使用

          Maven項(xiàng)目中引入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:
            enabletrue
            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)閉,所以這里定義一個(gè)變量
               */
              private Boolean enable;

              /**
               * 項(xiàng)目應(yīng)用名
               */
              private String applicationName;

              /**
               * 項(xiàng)目版本信息
               */
              private String applicationVersion;

              /**
               * 項(xiàng)目描述信息
               */
              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

          一個(gè)完整詳細(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)閉,可以通過(guò)變量控制
                          .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 頁(yè)面上半部分展示信息
               */
              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è)置,所有攔截器都會(huì)自動(dòng)加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

          一些常用注解說(shuō)明

          • @Api:用在controller類,描述API接口
          • @ApiOperation:描述接口方法
          • @ApiModel:描述對(duì)象
          • @ApiModelProperty:描述對(duì)象屬性
          • @ApiImplicitParams:描述接口參數(shù)
          • @ApiResponses:描述接口響應(yīng)
          • @ApiIgnore:忽略接口方法

          示例

          項(xiàng)目Demo:springfox-swagger

          效果圖:example

          參考

          • 在 Spring Boot 項(xiàng)目中使用 Swagger 文檔
          • Springfox 3.0.0(包含springfox-swagger2-3.0.0)即OpenAPI 3的發(fā)布與系統(tǒng)集成

          推薦文章

          更多項(xiàng)目源碼


          瀏覽 32
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <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>
                  国产乱伦A片 | 国产毛片一区 | 亚洲.无码.变态.欧美.中文 | 日韩人妻无码一区二区 | 国产高清色情 |