Springboot 升級(jí)帶來(lái)的Swagger異常

當(dāng)升級(jí)到Springboot 2.6.0 以上的版本后挨稿,Swagger 就不能正常工作了, 啟動(dòng)時(shí)報(bào)如下錯(cuò)誤墩虹。當(dāng)然如果你再使用sping boot ActuatorSpringfox, 也會(huì)引起相關(guān)的NPE error. (github issue: https://github.com/springfox/springfox/issues/3462)

NFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: Caused by: org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at java.lang.Iterable.forEach(Iterable.java:75)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: at com.ebay.adscollection.app.AdstrackingcollectionApplication.main(AdstrackingcollectionApplication.java:12)
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: ... 14 more
INFO | jvm 1 | 2022/04/27 21:47:05 | WrapperJarApp: Caused by: java.lang.NullPointerException

下面就一一說(shuō)明怎么解決

路徑匹配策略

報(bào)錯(cuò)原因:
springboot2.6.0中將SpringMVC 默認(rèn)路徑匹配策略從AntPathMatcher 更改為PathPatternParser涤浇,導(dǎo)致出錯(cuò)

解決:
在 application.properties 文件中指定spring.mvc.pathmatch.matching-strategy=ant_path_matcher

Actuator

在Springboot 2.6 里Actuator 指定了ant_path_matcher, 并且沒(méi)有辦法通過(guò)配置的方式來(lái)切換津畸。 我們可以通過(guò)定義bean 的方式來(lái)實(shí)現(xiàn)強(qiáng)制mapping蠢护。

@Bean
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
    List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
    Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
    allEndpoints.addAll(webEndpoints);
    allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
    allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
    String basePath = webEndpointProperties.getBasePath();
    EndpointMapping endpointMapping = new EndpointMapping(basePath);
    boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
    return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
}


private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
    return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
}

springfox

Springfox-swagger2:jar:3.0.0 在 spring boot 2.6.x不在支持,而是轉(zhuǎn)向springdoc
因此就在springboot 2.6.x , spring doc 應(yīng)該去掉箍土,而是用 springdoc-openapi-ui 替換逢享。

   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-ui</artifactId>
      <version>1.6.8</version>
   </dependency>

替換掉 swagger 2 annotations ,選用wagger 3 annotations wagger 3 annotations 報(bào)名是 io.swagger.v3.oas.annotations.

@Api → @Tag

@ApiIgnore → @Parameter(hidden = true) or @Operation(hidden = true) or @Hidden

@ApiImplicitParam → @Parameter

@ApiImplicitParams → @Parameters

@ApiModel → @Schema

@ApiModelProperty(hidden = true) → @Schema(accessMode = READ_ONLY)

@ApiModelProperty → @Schema

@ApiOperation(value = "foo", notes = "bar") → @Operation(summary = "foo", description = "bar")

@ApiParam → @Parameter

@ApiResponse(code = 404, message = "foo") → @ApiResponse(responseCode = "404", description = "foo")

如果你在application 里吴藻,不是用springfox 的dependency瞒爬, 而是自己定義多個(gè)Docket

@Bean
  public Docket publicApi() {
      return new Docket(DocumentationType.SWAGGER_2)
              .select()
              .apis(RequestHandlerSelectors.basePackage("org.github.springshop.web.public"))
              .paths(PathSelectors.regex("/public.*"))
              .build()
              .groupName("springshop-public")
              .apiInfo(apiInfo());
  }

  @Bean
  public Docket adminApi() {
      return new Docket(DocumentationType.SWAGGER_2)
              .select()
              .apis(RequestHandlerSelectors.basePackage("org.github.springshop.web.admin"))
              .paths(PathSelectors.regex("/admin.*"))
              .apis(RequestHandlerSelectors.withMethodAnnotation(Admin.class))
              .build()
              .groupName("springshop-admin")
              .apiInfo(apiInfo());
  }

那么就要改成

@Bean
  public GroupedOpenApi publicApi() {
      return GroupedOpenApi.builder()
              .group("springshop-public")
              .pathsToMatch("/public/**")
              .build();
  }
  @Bean
  public GroupedOpenApi adminApi() {
      return GroupedOpenApi.builder()
              .group("springshop-admin")
              .pathsToMatch("/admin/**")
              .addMethodFilter(method -> method.isAnnotationPresent(Admin.class))
              .build();
  }

如果只有一個(gè)Docket, 則要改成如下,用OpenAPI 而不是GroupedOpenApi

@Bean
  public OpenAPI springShopOpenAPI() {
      return new OpenAPI()
              .info(new Info().title("SpringShop API")
              .description("Spring shop sample application")
              .version("v0.0.1")
              .license(new License().name("Apache 2.0").url("http://springdoc.org")))
              .externalDocs(new ExternalDocumentation()
              .description("SpringShop Wiki Documentation")
              .url("https://springshop.wiki.github.org/docs"));
  }

同時(shí)設(shè)置參數(shù)在spring.factories 文件

springdoc.packagesToScan=package1, package2
springdoc.pathsToMatch=/v1, /api/balance/**

其他

If the swagger-ui is served behind a proxy:

To customise the Swagger UI:

To hide an operation or a controller from documentation:

refer link:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市侧但,隨后出現(xiàn)的幾起案子矢空,更是在濱河造成了極大的恐慌,老刑警劉巖俊犯,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件妇多,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡燕侠,警方通過(guò)查閱死者的電腦和手機(jī)者祖,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)绢彤,“玉大人七问,你說(shuō)我怎么就攤上這事∶2埃” “怎么了械巡?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)饶氏。 經(jīng)常有香客問(wèn)我讥耗,道長(zhǎng),這世上最難降的妖魔是什么疹启? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任古程,我火速辦了婚禮,結(jié)果婚禮上喊崖,老公的妹妹穿的比我還像新娘挣磨。我一直安慰自己,他們只是感情好荤懂,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布茁裙。 她就那樣靜靜地躺著,像睡著了一般节仿。 火紅的嫁衣襯著肌膚如雪晤锥。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,631評(píng)論 1 305
  • 那天粟耻,我揣著相機(jī)與錄音查近,去河邊找鬼。 笑死挤忙,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的谈喳。 我是一名探鬼主播册烈,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了赏僧?” 一聲冷哼從身側(cè)響起大猛,我...
    開(kāi)封第一講書(shū)人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎淀零,沒(méi)想到半個(gè)月后挽绩,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡驾中,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年唉堪,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片肩民。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡唠亚,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出持痰,到底是詐尸還是另有隱情灶搜,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布工窍,位于F島的核電站割卖,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏患雏。R本人自食惡果不足惜鹏溯,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望纵苛。 院中可真熱鬧剿涮,春花似錦、人聲如沸攻人。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)怀吻。三九已至瞬浓,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蓬坡,已是汗流浹背猿棉。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留屑咳,地道東北人萨赁。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像兆龙,于是被迫代替她去往敵國(guó)和親杖爽。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容