Resolving Swagger Configuration Issues in Spring Boot Applications
Problem: org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
Method 1
Dependency Configuration:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
In your Swagger configuration class, add the @EnableWebMvc annotation to explicitly enable Spring MVC annotation-driven configuration. This ensures better integration between Swagger and Spring MVC for proper API documentation generation.
Analysis:
- Swagger requires tight integration with Spring MVC to automatically scan and register RESTful interfaces from controllers.
- @EnableWebMvc activates Spring MVC's annotation-driven functionality, which is crucial for Swagger to parse annotations in controllers.
- This annotation overrides Spring Boot's auto-configuration, requiring manual configuration of some settings previously provided by auto-configuration.
- Static resource handling may need additional configuration since @EnableWebMvc affects how static resources are served.
Method 2
Dependency Configuration:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.7</version>
</dependency>
Configuration Class:
package com.example.apidoc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
@Configuration
@EnableSwagger2WebMvc
public class ApiDocConfig {
@Bean(value = "apiDocumentation")
public Docket apiDocumentation() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiDetails())
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiDetails() {
return new ApiInfoBuilder()
.title("API Documentation")
.contact(new Contact("Tech Team", "www.example.com", "support@example.com"))
.description("Service API Documentation")
.termsOfServiceUrl("No terms of service")
.version("1.0")
.build();
}
}
Access URL: localhost:configured-port/api/doc.html
Note: For Spring Boot version >= 2.6.x, add the following configuration:
spring:
mvc:
path-match:
matching-strategy: ANT_PATH_MATCHER