Search code examples
springspring-bootswaggerswagger-ui

Configuring Swagger UI in Spring Boot


I have an issue regarding the opening of the Swagger interface at the following link: http://localhost:8080/swagger-ui/index.html

Currently, when I try to access it, I receive a 500 error, and I'm not sure how to resolve it. I have tried several solutions so far, but without success.

Java:

package com.ishotit.api;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableJpaRepositories
@SpringBootApplication
public class ApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiApplication.class, args);
    }

}

@Configuration(proxyBeanMethods = false)
@EnableWebMvc
class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("*").allowedHeaders("*");
    }
}


@Configuration
class SpringFoxConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

application.properties:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.url=jdbc:postgresql://localhost:5432/ishotit
spring.datasource.username=ishotit
spring.datasource.password=apipassword
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
springdoc.enable-native-support=true

Solution

  • Its better to use springdoc-openapi for Spring Boot 3.x

    just remove previous configurations of SpringFoxConfig and delete its dependencies.

    Then add this dependency to your pom file

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

    And then run

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