spring-bootswagger

How to use both @RestControllerAdvice and Swagger UI in Spring boot


I have a very simple Spring boot project contains Swagger UI:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.5.0</version>
</dependency>

After I setting a class has @RestControllerAdvice, trying to view swagger UI throw an exception: enter image description here

And the log is

java.lang.NoSuchMethodError: 'void org.springframework.web.method.ControllerAdviceBean.<init>(java.lang.Object)'

The tree:

└───com
    └───cuong02n
        └───test
            │   App.java
            │
            ├───controller
            │       CourseController.java
            │       StudentController.java
            │
            └───exception
                    CustomExceptionHandler.java <-- The @RestControllerAdvice here
                    StudentException.java

After reading and trying some solutions by adding basePackage, I still can't access Swagger UI.

Update

The pom.xml is:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cuong02n</groupId>
    <artifactId>test-controller-advice-swagger</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test-controller-advice-swagger</name>
    <description>test-controller-advice-swagger</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>2.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Solution

  • According to @M.Deinum, this caught by incompatible, I am using spring-boot-starter-parent 3.4.0 and springdoc-openapi-starter-webmvc-ui 2.5.0. They are conflicted.

    My solution is downgrade spring to 3.3.5 and it works well.