How to run Swagger 3 on Spring Boot 3
Asked Answered
A

15

49

Using a fresh Spring Initialzr with Java17 and Spring Boot 3.0.0, and an extra addition to the pom.xml for Springfox Swagger 3, I can't for the life of me get Swagger pages to work. Instead, I get the whitelabel error page with 404.

Pom.xml

<?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.0.0</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>17</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

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

The standard Swagger URLs as defined in this Github Issues page aren't working for the above pom.xml project.

Anatol answered 29/11, 2022 at 12:49 Comment(1)
Following Spring Boot 3+ Swagger example helped me a lot - javainuse.com/boot3/sec/9Diley
A
86

I had given up and went to use Spring Boot 2.7 after posting the question. But, after seeing Dmitriy's answer though, I checked Springdoc one last time and found that Springdoc v2 does support Spring Boot 3.

Essentially, one has to place the following in their pom:

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

Then one can access the Swagger page using the following URL: http://localhost:8080/swagger-ui.html (Don't forget to add context path if you need it). For some reason, when opening, it redirects to http://localhost:8080/swagger-ui/index.html although going for that initially returned 404...

Anatol answered 30/11, 2022 at 11:19 Comment(3)
Have you found any other solution to it except for downgrading the spring boot version @AhmedImprecate
Hi @TabishHafeez. As the answer says, Spring Boot 3.0 is covered by SpringDoc 2.0Anatol
Migrating to Springdoc ist the way to go. Springfox is essencially abandoned, since the last update in the GitHub repository has been in 2020.Cloverleaf
F
15

in addition to adding springdoc-openapi-starter-webmvc-ui (v2.0.2 for me) as indicated in the accepted answer, I also needed to remove org.springdoc:springdoc-openapi-ui:1.6.13 .

It was there because I had tried it before. If present, there's still a non Jakarta reference that Spring tries to resolve (and fails to do so).

I also needed to add this dependency, otherwise I would have a nasty message at startup (version is resolved by Spring Boot BOM) :

implementation group: 'org.hibernate.validator', name: 'hibernate-validator'
Festive answered 16/12, 2022 at 18:29 Comment(3)
You needed hibernate for a bare bones Spring Boot 3 hello world app with swagger?Anatol
not hibernate, but hibernate-validator, which is the standard implementation for Java Bean validationFestive
@VincentF You may add a dependency on spring-boot-starter-validation which already provides (read abstracts) hibernate-validatorAkim
C
12

I agreed with @Ahmed Tawfik because I also faced the same. But today I tried that same approach with the new version of "springdoc-openapi-starter-webmvc-ui" dependency and Spring Boot 3.0.2-SNAPSHOT.

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

because the previous one "springdoc-openapi-ui" is changed to the above one.

Also, include below the path to the security config for swagger UI.

"/v3/api-docs/**","/swagger-ui/**"

For my project,

@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http.cors(AbstractHttpConfigurer::disable)
                .csrf(AbstractHttpConfigurer::disable)
                .exceptionHandling(exceptionHandlingConfigurer -> exceptionHandlingConfigurer.authenticationEntryPoint(unauthorizedHandler))
                .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> {
                            try {
                                authorizationManagerRequestMatcherRegistry
                                        .requestMatchers(HttpMethod.POST, POST_AUTH_WHITELIST).permitAll()
                                        .requestMatchers(HttpMethod.GET, GET_AUTH_WHITELIST).permitAll()
                                        .requestMatchers("/v3/api-docs/**", "/swagger-ui/**").permitAll()
                                        .anyRequest()
                                        .authenticated()
                                        .and()
                                        .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
                            } catch (Exception e) {
                                throw new ResourceNotFoundException(e.getMessage());
                            }
                        }
                )
                .formLogin(AbstractHttpConfigurer::disable)
                .httpBasic(AbstractHttpConfigurer::disable).addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .authenticationProvider(daoAuthenticationProvider()).build();
    }

The swagger UI link will be:

http://server:port/context-path/swagger-ui.html

Please adjust the server, port, and context-path regarding your personal changes.

All the above steps are working fine with my project. I don't need extra configuration.

Also, you can add the custom path (Optional):

springdoc.swagger-ui.path=/swagger-ui.html

Here is the Official Documentation of OpenApi 3 and Spring Boot : https://springdoc.org/v2/#features

In the above documentation, you can explore additional configurations and other things also.

Happy Learning! ✌️

Coffle answered 23/12, 2022 at 8:47 Comment(1)
This need to be the accepted answer at 09/01/2023Regality
R
12

Springdoc is working with Spring boot 3.0.1

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

Default URL: http://localhost:8080/swagger-ui/index.html

Rearrange answered 27/12, 2022 at 2:42 Comment(1)
Duplicate answerGenetics
P
7

Lastest springfox-boot-starter version 3.0.0 and springdoc-openapi-ui 1.6.13

seems not to support spring-boot 3.

We need to wait until the new version adopts jakarta.servlet package

Perique answered 30/11, 2022 at 5:44 Comment(3)
Here is already a GitHub issue opened for this case: github.com/springfox/springfox/issues/3983 (and several duplicate-issues)Agueda
This is not true any more, use springdoc openapi 2.x.xHoxsie
Aggre. <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.0.2</version> </dependency>Perique
S
6

For Gradle you can add this:

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.0'
Surmullet answered 13/12, 2022 at 11:51 Comment(0)
N
6

for Spring Boot 3, use springdoc-openapi v2

Here is the sample steps that is working on Spring Boot 3 and suports JWT based Authentication:

Add the following dependency in the pom.xml file:

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

Create a new class called OpenApiConfig. In this example annotation-based configuration is used, but it can also be configured programmatically.

@Configuration
@OpenAPIDefinition(info = @Info(title = "REST API", version = "1.0",
        description = "REST API description...",
        contact = @Contact(name = "Name Surname")),
        security = {@SecurityRequirement(name = "bearerToken")}
)
@SecuritySchemes({
        @SecurityScheme(name = "bearerToken", type = SecuritySchemeType.HTTP, 
                        scheme = "bearer", bearerFormat = "JWT")
})

Then update your SecurityConfig class by adding necessary urls for access permission:

private static final String[] AUTH_WHITELIST = {
        "/api/v1/auth/**",
        "/v3/api-docs/**",
        "/v3/api-docs.yaml",
        "/swagger-ui/**",
        "/swagger-ui.html"
};

@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception{
    httpSecurity
            // ...
            .authorizeHttpRequests()
            .requestMatchers(AUTH_WHITELIST).permitAll()
            .anyRequest().authenticated();
    // ...
}

Run the app and access the documentation on http://localhost:8080/swagger-ui/index.html

Nunez answered 18/3, 2023 at 8:50 Comment(0)
S
3

For Spring Boot 3 and Above we have this dependency to add

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

and for a project that contains spring security, We need to permit the following path in order to ignore the @AuthenticationPrincipal parameter.

    private static final String[] AUTH_WHITELIST = {
        "/api/v1/auth/**",
        "/v3/api-docs/**",
        "/v3/api-docs.yaml",
        "/swagger-ui/**",
        "/swagger-ui.html"
};

for more resource 👉watch this or read this document

Smaragdine answered 14/4, 2023 at 6:21 Comment(0)
A
2

The latest version of springdoc-openapi is compatiable with Springboot 3 (jakarta) changes. Using the latest version solved the problem for me.

https://springdoc.org/v2/

Abrade answered 6/3, 2023 at 9:46 Comment(0)
T
1

Following dependencies working fine to me.

<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>
    <groupId>com.sample.app</groupId>
    <artifactId>hello-world</artifactId>
    <version>1.0.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


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

    </dependencies>
</project>
Tremble answered 16/1, 2023 at 8:41 Comment(0)
K
1

seems like the springfox version of swagger is not working for spring 3.0 . An alternative is openAPI. Add following dependency to make it work

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'
Keciakeck answered 14/3, 2023 at 9:36 Comment(0)
K
0

Use Open API instead swagger for Spring v3.0. Follow this document Open API Docs

enter image description here

Kinetics answered 30/12, 2022 at 8:15 Comment(2)
Your link is dead.Skew
Fixed the problem with linkKinetics
G
0
pom.xml
<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  <version>2.0.3</version>
</dependency>

application.properties

#springdoc.api-docs.enabled=false
#springdoc.swagger-ui.enabled=false

springdoc.swagger-ui.path=/bezkoder-documentation
springdoc.api-docs.path=/bezkoder-api-docs

springdoc.packages-to-scan=com.bezkoder.spring.swagger.controller
springdoc.swagger-ui.tryItOutEnabled=true
springdoc.swagger-ui.operationsSorter=method
springdoc.swagger-ui.tagsSorter=alpha
springdoc.swagger-ui.filter=true
– Use api-docs.enabled=false if you want to disable springdoc-openapi endpoints.
– Use swagger-ui.enabled=false to disable the swagger-ui endpoint.

– api-docs.path is for custom path of the OpenAPI documentation in Json format. Now it is http://localhost:8080/bezkoder-api-docs.

– swagger-ui.path is for custom path of the Swagger documentation. If you visit http://localhost:8080/bezkoder-documentation, the browser will redirect you to http://localhost:8080/swagger-ui/index.html

– packages-to-scan=packageA,packageB: list of packages to scan with comma separated.
We also have packages-to-exclude, paths-to-match, paths-to-exclude.

– swagger-ui.tryItOutEnabled if you want to enable “Try it out” section by default
Gaberlunzie answered 28/8, 2023 at 11:51 Comment(0)
S
0

You can try this if your system has jdk17 and your project is on springboot 3

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

#pom.xml

server.port=8081
springfox.documentation.swagger-ui.enabled=true
#OpenAPI Properties
springdoc:
api-docs:
swagger-ui:
path: /swagger-ui.html
enabled: true

#Application.properties

For more information and complete setup file you can refer this website Swagger in spring boot 3 How to integrate It

Why should anyone consider this answer? Earlier I also faced difficulties to setup swagger in my latest java17 application and I found this method by doing r&d. And it worked without fail so that I thinks this answer should help everyone.

Sorcim answered 1/2, 2024 at 15:26 Comment(1)
Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?Remorse
P
-1

I was not able to run Swagger (using springdoc-openapi-starter-webmvc-ui 2.2.0) with Spring Boot 3. I finally found that the problem was due to a configuration class extending WebMvcConfigurationSupport.

Protection answered 10/11, 2023 at 8:44 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Dalt

© 2022 - 2025 — McMap. All rights reserved.