1. 添加 pom 依赖:
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger2</artifactId>
- <version>3.0.0</version>
- </dependency>
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger-ui</artifactId>
- <version>3.0.0</version>
- </dependency>
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-boot-starter</artifactId>
- <version>3.0.0</version>
- </dependency>
2. Swagger 配置:
- @Configuration
- @EnableSwagger2
- public class SwaggerConfig implements WebMvcConfigurer {
- @Bean
- public Docket createRestApi() {
- ApiInfo apiInfo =
- new ApiInfoBuilder()
- .title("API")
- .description("Tacos API")
- .version("1.0")
- .contact(new Contact("Admin", "https://github.com/yutils", "3373217@qq.com"))
- .license("我的首页")
- .licenseUrl("https://weibo.com/32005200")
- .build();
- return new Docket(DocumentationType.SWAGGER_2)
- .apiInfo(apiInfo)
- .select()
- .apis(RequestHandlerSelectors.basePackage("tacos.controller"))
- .paths(PathSelectors.any())
- .build();
- }
- @Override
- public void addResourceHandlers(ResourceHandlerRegistry registry) {
- registry.
- addResourceHandler("/swagger-ui/**")
- .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
- .resourceChain(false);
- }
- @Override
- public void addViewControllers(ViewControllerRegistry registry) {
- registry.addViewController("/swagger-ui/")
- .setViewName("forward:" + "/swagger-ui/index.html");
- }
- }
3. 排障:
✘
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException:Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.toString()" because the return value of "springfox.documentation.spi.service.contexts.Orderings.patternsCondition(springfox.documentation.RequestHandler)" is null
这个问题是Spring Boot 2.6及以上版本,确实将路径匹配规则的默认实现从AntPathMatcher更改为PathPatternMatcher。这可能导致在使用一些旧版本的代码或配置时出现问题。
如果你想在Spring Boot 2.6+版本中恢复旧的路径匹配规则(即使用AntPathMatcher),可以通过配置spring.mvc.pathmatch.matching-strategy属性来解决问题。
在application.properties文件中,添加以下配置:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
在application.yml文件中,添加以下配置:
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
通过将spring.mvc.pathmatch.matching-strategy属性设置为ant_path_matcher,你可以告诉Spring Boot使用旧的AntPathMatcher作为路径匹配策略。
这样做将恢复与之前版本相同的路径匹配行为,并解决由此更改引起的问题。请确保在升级到新版本时,检查和更新代码和配置,以适应新的路径匹配规则。