I have found this simple way to customize Swagger into a Spring Boot application with just two files copied from original springfox-swagger-ui

First of all i have disabled @Configuration from SwaggerConfig.java:

//@Configuration <-- Attention, disable Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .ignoredParameterTypes(Pageable.class)
                .select().apis(RequestHandlerSelectors.any())
                .paths(regex("/v1/.*"))
                .build();

    }
}

Then I have extended a WebMvcConfigurerAdapter:

@Configuration
@Import(SwaggerConfig.class)
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/doc/v1/**").addResourceLocations("classpath:/doc/v1/");
        registry.addResourceHandler("/doc/v1/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

Then I have just copied original file swagger-ui.html into src/main/resources/doc/v1/api.html with just a simple modification. I have substituted this line:

<script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>

with this line:

<script src='js/swagger.js' type='text/javascript'></script>

This is my api.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
    <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
    <link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>

    <script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>

    <script src='js/springfox.js' type='text/javascript'></script>
</head>

<body class="swagger-section">
<div id='header'>
    <div class="swagger-ui-wrap">
        <a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30" src="webjars/springfox-swagger-ui/images/logo_small.png" /><span class="logo__title">swagger</span></a>
        <form id='api_selector'>
            <div class='input'>
                <select id="select_baseUrl" name="select_baseUrl"/>
            </div>
            <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
            <div id='auth_container'></div>
            <div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
        </form>
    </div>
</div>

<div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>

After that i have copied original springfox.js into src/main/resources/doc/v1/js/springfox.js where i have changed these lines:

"baseUrl": function() {
      var urlMatches = /(.*)\/swagger-ui.html.*/.exec(window.location.href);
      return urlMatches[1];
    },

with these lines:

"baseUrl": function() {
            return window.location.origin;
        },

This is my complete springfox.js

$(function() {
    var springfox = {
        "baseUrl": function() {
            return window.location.origin;
        },
        "securityConfig": function(cb) {
            $.getJSON(this.baseUrl() + "/swagger-resources/configuration/security", function(data) {
                cb(data);
            });
        },
        "uiConfig": function(cb) {
            $.getJSON(this.baseUrl() + "/swagger-resources/configuration/ui", function(data) {
                cb(data);
            });
        }
    };
    window.springfox = springfox;
    window.oAuthRedirectUrl = springfox.baseUrl() + '/webjars/springfox-swagger-ui/o2c.html';

    window.springfox.uiConfig(function(data) {
        window.swaggerUi = new SwaggerUi({
            dom_id: "swagger-ui-container",
            validatorUrl: data.validatorUrl,
            supportedSubmitMethods: data.supportedSubmitMethods || ['get', 'post', 'put', 'delete', 'patch'],
            docExpansion: data.docExpansion || 'none',
            jsonEditor: JSON.parse(data.jsonEditor) || false,
            apisSorter: data.apisSorter || 'alpha',
            defaultModelRendering: data.defaultModelRendering || 'schema',
            showRequestHeaders: data.showRequestHeaders || true,
            timeout: data.requestTimeout,
            onComplete: function(swaggerApi, swaggerUi) {

                initializeSpringfox();

                if (window.SwaggerTranslator) {
                    window.SwaggerTranslator.translate();
                }

                $('pre code').each(function(i, e) {
                    hljs.highlightBlock(e)
                });

            },
            onFailure: function(data) {
                log("Unable to Load SwaggerUI");
            },
        });

        initializeBaseUrl();

        function addApiKeyAuthorization(security) {
            var apiKeyVehicle = security.apiKeyVehicle || 'query';
            var apiKeyName = security.apiKeyName || 'api_key';
            var apiKey = security.apiKey || '';
            if (apiKey && apiKey.trim() != "") {
                var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization(apiKeyName, apiKey, apiKeyVehicle);
                window.swaggerUi.api.clientAuthorizations.add(apiKeyName, apiKeyAuth);
                log("added key " + apiKey);
            }
        }

        function log() {
            if ('console' in window) {
                console.log.apply(console, arguments);
            }
        }

        function oAuthIsDefined(security) {
            return security.clientId
                && security.clientSecret
                && security.appName
                && security.realm;
        }

        function initializeSpringfox() {
            var security = {};
            window.springfox.securityConfig(function(data) {
                security = data;
                addApiKeyAuthorization(security);
                if (typeof initOAuth == "function" && oAuthIsDefined(security)) {
                    initOAuth(security);
                }
            });
        }
    });

    $('#select_baseUrl').change(function() {
        window.swaggerUi.headerView.trigger('update-swagger-ui', {
            url: $('#select_baseUrl').val()
        });
    });

    function maybePrefix(location, withRelativePath) {
        var pat = /^https?:\/\//i;
        if (pat.test(location)) {
            return location;
        }
        return withRelativePath + location;
    }

    function initializeBaseUrl() {
        var relativeLocation = springfox.baseUrl();

        $('#input_baseUrl').hide();

        $.getJSON(relativeLocation + "/swagger-resources", function(data) {

            var $urlDropdown = $('#select_baseUrl');
            $urlDropdown.empty();
            $.each(data, function(i, resource) {
                var option = $('<option></option>')
                    .attr("value", maybePrefix(resource.location, relativeLocation))
                    .text(resource.name + " (" + resource.location + ")");
                $urlDropdown.append(option);
            });
            $urlDropdown.change();
        });

    }

});

This is my folder structure

Now you have just to run application and go to http://localhost:8080/doc/v1/api.html

Answer from Antonio Saracino on Stack Overflow
Top answer
1 of 2
13

I have found this simple way to customize Swagger into a Spring Boot application with just two files copied from original springfox-swagger-ui

First of all i have disabled @Configuration from SwaggerConfig.java:

//@Configuration <-- Attention, disable Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .ignoredParameterTypes(Pageable.class)
                .select().apis(RequestHandlerSelectors.any())
                .paths(regex("/v1/.*"))
                .build();

    }
}

Then I have extended a WebMvcConfigurerAdapter:

@Configuration
@Import(SwaggerConfig.class)
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/doc/v1/**").addResourceLocations("classpath:/doc/v1/");
        registry.addResourceHandler("/doc/v1/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

Then I have just copied original file swagger-ui.html into src/main/resources/doc/v1/api.html with just a simple modification. I have substituted this line:

<script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>

with this line:

<script src='js/swagger.js' type='text/javascript'></script>

This is my api.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
    <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
    <link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>

    <script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>

    <script src='js/springfox.js' type='text/javascript'></script>
</head>

<body class="swagger-section">
<div id='header'>
    <div class="swagger-ui-wrap">
        <a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30" src="webjars/springfox-swagger-ui/images/logo_small.png" /><span class="logo__title">swagger</span></a>
        <form id='api_selector'>
            <div class='input'>
                <select id="select_baseUrl" name="select_baseUrl"/>
            </div>
            <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
            <div id='auth_container'></div>
            <div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
        </form>
    </div>
</div>

<div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>

After that i have copied original springfox.js into src/main/resources/doc/v1/js/springfox.js where i have changed these lines:

"baseUrl": function() {
      var urlMatches = /(.*)\/swagger-ui.html.*/.exec(window.location.href);
      return urlMatches[1];
    },

with these lines:

"baseUrl": function() {
            return window.location.origin;
        },

This is my complete springfox.js

$(function() {
    var springfox = {
        "baseUrl": function() {
            return window.location.origin;
        },
        "securityConfig": function(cb) {
            $.getJSON(this.baseUrl() + "/swagger-resources/configuration/security", function(data) {
                cb(data);
            });
        },
        "uiConfig": function(cb) {
            $.getJSON(this.baseUrl() + "/swagger-resources/configuration/ui", function(data) {
                cb(data);
            });
        }
    };
    window.springfox = springfox;
    window.oAuthRedirectUrl = springfox.baseUrl() + '/webjars/springfox-swagger-ui/o2c.html';

    window.springfox.uiConfig(function(data) {
        window.swaggerUi = new SwaggerUi({
            dom_id: "swagger-ui-container",
            validatorUrl: data.validatorUrl,
            supportedSubmitMethods: data.supportedSubmitMethods || ['get', 'post', 'put', 'delete', 'patch'],
            docExpansion: data.docExpansion || 'none',
            jsonEditor: JSON.parse(data.jsonEditor) || false,
            apisSorter: data.apisSorter || 'alpha',
            defaultModelRendering: data.defaultModelRendering || 'schema',
            showRequestHeaders: data.showRequestHeaders || true,
            timeout: data.requestTimeout,
            onComplete: function(swaggerApi, swaggerUi) {

                initializeSpringfox();

                if (window.SwaggerTranslator) {
                    window.SwaggerTranslator.translate();
                }

                $('pre code').each(function(i, e) {
                    hljs.highlightBlock(e)
                });

            },
            onFailure: function(data) {
                log("Unable to Load SwaggerUI");
            },
        });

        initializeBaseUrl();

        function addApiKeyAuthorization(security) {
            var apiKeyVehicle = security.apiKeyVehicle || 'query';
            var apiKeyName = security.apiKeyName || 'api_key';
            var apiKey = security.apiKey || '';
            if (apiKey && apiKey.trim() != "") {
                var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization(apiKeyName, apiKey, apiKeyVehicle);
                window.swaggerUi.api.clientAuthorizations.add(apiKeyName, apiKeyAuth);
                log("added key " + apiKey);
            }
        }

        function log() {
            if ('console' in window) {
                console.log.apply(console, arguments);
            }
        }

        function oAuthIsDefined(security) {
            return security.clientId
                && security.clientSecret
                && security.appName
                && security.realm;
        }

        function initializeSpringfox() {
            var security = {};
            window.springfox.securityConfig(function(data) {
                security = data;
                addApiKeyAuthorization(security);
                if (typeof initOAuth == "function" && oAuthIsDefined(security)) {
                    initOAuth(security);
                }
            });
        }
    });

    $('#select_baseUrl').change(function() {
        window.swaggerUi.headerView.trigger('update-swagger-ui', {
            url: $('#select_baseUrl').val()
        });
    });

    function maybePrefix(location, withRelativePath) {
        var pat = /^https?:\/\//i;
        if (pat.test(location)) {
            return location;
        }
        return withRelativePath + location;
    }

    function initializeBaseUrl() {
        var relativeLocation = springfox.baseUrl();

        $('#input_baseUrl').hide();

        $.getJSON(relativeLocation + "/swagger-resources", function(data) {

            var $urlDropdown = $('#select_baseUrl');
            $urlDropdown.empty();
            $.each(data, function(i, resource) {
                var option = $('<option></option>')
                    .attr("value", maybePrefix(resource.location, relativeLocation))
                    .text(resource.name + " (" + resource.location + ")");
                $urlDropdown.append(option);
            });
            $urlDropdown.change();
        });

    }

});

This is my folder structure

Now you have just to run application and go to http://localhost:8080/doc/v1/api.html

2 of 2
5

Solution if you are using maven:

  • You should copy swagger-ui.html into src/main/webapp

  • Make your editions or replace screen.css by your theme.css

Than add these code into your pom.xml:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <webResources>
                    <resource>
                        <directory>${basedir}/src/main/webapp</directory>
                        <filtering>true</filtering>
                        <includes>
                            <include>*.css</include>
                            <include>*.html</include>
                        </includes>
                    </resource>
                </webResources>
            </configuration>
        </plugin>
    </plugins>
</build>
🌐
GitHub
github.com › springdoc › springdoc-openapi › issues › 1487
How to customize the Swagger UI files · Issue #1487 · springdoc/springdoc-openapi
February 3, 2022 - I'm using Spring Boot project with Gradle and I'm trying to understand how to modify the Swagger UI HTML/CSS/JS files so I can customize it so it looks similar to my project. I tried puttin...
Author   mjovanc
Discussions

Configuring Swagger UI with Spring Boot - Stack Overflow
I am trying to configure Swagger UI with my Spring boot application. Although the v2/api-docs seems to be loading properly, the http://localhost:8080/swagger-ui.html does not load my annotated REST... More on stackoverflow.com
🌐 stackoverflow.com
spring boot - How to customize Swagger Top Bar - Stack Overflow
I don't know what a React file type is postfixed with aka MyLayout.js .jsx or whatever. I also don't know where to place this custom layout file in the Spring Boot project. Do I compile it? If so how? ... In standalone Swagger UI, you would use the urls config parameter to render the "Select ... More on stackoverflow.com
🌐 stackoverflow.com
spring - How do I configure a custom URL for the springdoc swagger-ui HTML page? - Stack Overflow
I had a similar task for Spring Boot 2.5.6 and springdoc-openapi-webflux-ui 1.5.12. I've found several possible solutions for myself. Maybe it will be helpful for somebody else. The straightforward way is to set property springdoc.swagger-ui.path=/custom/path. More on stackoverflow.com
🌐 stackoverflow.com
With Spring-Boot and WebJars how do I configure Swagger-UI - Stack Overflow
I have a Spring-Boot Application, generating swagger JSON at /contextPath/v2/api-docs. Due to security concerns I have installed Swagger-UI from webJars version: 4.1.3. Swagger-UI no longer allows ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Nodalpoint
nodalpoint.com › home › blog › configure swaggerui in a springboot application
Configure SwaggerUI in a SpringBoot application - Nodalpoint
February 21, 2025 - Here’s how you can configure Swagger UI for your Spring Boot API. In your pom.xml, include the following dependencies to integrate Springdoc OpenAPI: ... For any other SpringBoot version please check the related compatibility. Define a Spring Bean to set up the OpenAPI configuration, customizing details such as the API’s title, description, version, and licensing information:
Top answer
1 of 7
8

I had this issue today and fixed it by matching up the versions of my springfox-swagger2 and springfox-swagger-ui dependencies:

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
    </dependency>

There's very little other code to just get it up and running. One simple config class:

@Configuration
@EnableSwagger2
class SwaggerConfiguration {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.foo.samples.swaggersample"))
                .paths(PathSelectors.any())
                .build();
    }

}

And my application.properties

# location of the swagger json
springfox.documentation.swagger.v2.path=/swagger.json

(This is in Spring Boot).

2 of 7
2

Statement : Generate Swagger UI for the listing of all the REST APIs through Spring Boot Application.

Follow the below steps to generate the Swagger UI through Spring Boot application:

1. Add following dependency in pom.xml –

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
    </dependency>

2. Add the following piece of code in your main application class having the @EnableSwagger2 annotation.

    @EnableSwagger2
    @SpringBootApplication
    public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).select()  
           .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
           .paths(PathSelectors.any()).build().pathMapping("/")
           .apiInfo(apiInfo()).useDefaultResponseMessages(false);
    }

    @Bean
    public ApiInfo apiInfo() {
        final ApiInfoBuilder builder = new ApiInfoBuilder();
        builder.title("My Application API through Swagger UI").version("1.0").license("(C) Copyright Test")
        .description("List of all the APIs of My Application App through Swagger UI");
        return builder.build();
        }
    }

3. Add the below RootController class in your code to redirect to the Swagger UI page. In this way, you don’t need to put the dist folder of Swagger-UI in your resources directory.

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    @Controller
    @RequestMapping("/")
    public class RootController {
        @RequestMapping(method = RequestMethod.GET)
        public String swaggerUi() {
            return "redirect:/swagger-ui.html";
        }
    }

4. Being the final steps, add the @Api and @ApiOperation notation in all your RESTControllers like below –

    import static org.springframework.web.bind.annotation.RequestMethod.GET;
    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseStatus;
    import org.springframework.web.bind.annotation.RestController;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;

    @RestController
    @RequestMapping("/hello")
    @Api(value = "hello", description = "Sample hello world application")
    public class TestController {

        @ApiOperation(value = "Just to test the sample test api of My App Service")
        @RequestMapping(method = RequestMethod.GET, value = "/test")
        // @Produces(MediaType.APPLICATION_JSON)
        public String test() {
            return "Hello to check Swagger UI";
        }

        @ResponseStatus(HttpStatus.OK)
        @RequestMapping(value = "/test1", method = GET)
        @ApiOperation(value = "My App Service get test1 API", position = 1)
        public String test1() {
            System.out.println("Testing");
            if (true) {
                return "Tanuj";
            }
            return "Gupta";
        }
    }

Now your are done. Now to run your Spring Boot Application, go to browser and type localhost:8080. You will see Swagger UI having all the details of your REST APIs.

Happy Coding.
The source code of the above implementation is also on my blog if you feel like checking it out.

🌐
SpringDoc
springdoc.org
OpenAPI 3 Library for spring-boot
Since Spring Boot 2.2, this is the new property to handle reverse proxy headers: ... If you need to manually adjust the URL displayed in the Swagger UI, implement the ServerBaseUrlCustomizer interface.
🌐
Medium
medium.com › dev-spring › spring-boot-swagger-setup-0b023272c164
Spring boot Swagger setup
February 28, 2025 - For Spring Boot applications, the recommended library for OpenAPI (Swagger) documentation is Springdoc OpenAPI. <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.8.5</version> ...
🌐
iGreenData
igreendata.com.au › home › blogs › configuring swagger in spring boot application
Configuring Swagger in Spring Boot Application - iGreenData
October 7, 2021 - Note: For Spring boot 3 version, adding “springfox-boot-starter” dependency is enough and we don’t need to add swagger ui dependency and also not to include @EnableSwagger2 in the starter class. Then run command :mvn clean install to download the swagger dependency to your project. ... Need to define a Bean “Docket” to customize ...
Find elsewhere
🌐
Medium
medium.com › @samuelgbenga972 › basic-swagger-setup-for-spring-boot-application-755adc6e5a9b
Basic Swagger Setup for Spring Boot Application | by Samuelgbenga | Medium
August 9, 2024 - The OpenAPI instance, configured with the Info object, is used to generate user-friendly and informative API documentation. This metadata will appear in the OpenAPI documentation UI (such as Swagger UI), helping users understand the purpose and version of your API. By following these steps, you can integrate Swagger into your Spring Boot application using Springdoc OpenAPI.
🌐
Bell Software
bell-sw.com › blog › documenting-rest-api-with-swagger-in-spring-boot-3
How to use Swagger with Spring Boot
The beauty about springdoc-openapi library dependency is that it already includes Swagger UI, so we don’t have to configure the tool separately!
Top answer
1 of 2
7

I don't have a solution for a custom header/top bar using a custom Swagger YAML file. However, I achieved it using a custom Springdoc CSS file in one of my projects. To do this, follow these steps:

  1. Load your Swagger UI, open the developer console and navigate to the sources of the page. Download the swagger-ui.css file.

  2. Put this swagger-ui.css file in the resources folder of your Spring Boot project.

  3. Open the swagger-ui.css file and add following CSS (at the bottom of the file) to hide the topbar:

    .topbar {
        display: none;
    }
    
  4. Create new Controller, which is going to "host" your custom CSS file:

    @Controller
    public class CustomOpenApiUiController {
    
        @Value("classpath:swagger-ui.css")
        private Resource cssFile;
    
        @GetMapping(value = "/swagger-ui/swagger-ui.css")
        public void resourceCSS(HttpServletRequest request, HttpServletResponse response) {
            setResource(cssFile, response, "text/css;charset=UTF-8");
        }
    
        private void setResource(Resource resource, HttpServletResponse response, String contentType) {
            try {
                response.setHeader("content-type", contentType);
                response.setHeader("Pragma", "no-cache");
                byte[] file = IOUtils.toByteArray(Objects.requireNonNull(resource.getURI()));
                response.getOutputStream().write(file);
            } catch (Exception e) {
                log.error("Error occurred while loading the OpenAPI CSS file: {}", e.getMessage());
            }
        }
    }
    
  5. Load your Swagger UI again. The top bar should be gone. You can also check in the developer console, that your new CSS is applied to the .topbar class (which is responsible for the header you are trying to get rid of).

Now that you're in control of the CSS file, you can edit whatever you want.

2 of 2
0

add groups as follow in application.yml:

springdoc:
  version: '@springdoc.version@'
  swagger-ui:
    doc-expansion: none
    display-request-duration: true
    groups-order: ASC
  show-actuator: true        
  group-configs:            # add your groups here
    - group: all
      packagesToScan:
        - com.hung.swagger.controller
    - group: book
      paths-to-match: /store/**   
    - group: actuator
      paths-to-match: /actuator/**   
    - group: MyRestController
      paths-to-match: /api/my-rest-controller/**
    - group: MyController
      paths-to-match: /api/my-controller/**
🌐
Baeldung
baeldung.com › home › rest › setting up swagger 2 with a spring rest api using springfox
Setting Up Swagger 2 with a Spring REST API | Baeldung
November 12, 2025 - Additionally, without Spring Boot, we don’t have the luxury of auto-configuration of our resource handlers. Swagger UI adds a set of resources that we must configure as part of a class that extends WebMvcConfigurerAdapter and is annotated with @EnableWebMvc:
🌐
CodingTechRoom
codingtechroom.com › question › spring-boot-custom-swagger-ui
How to Customize Swagger UI in Spring Boot - CodingTechRoom
// Example of configuring SpringFox to customize Swagger UI import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } }
🌐
Medium
medium.com › @yohanesdwikiwitman › spring-boot-3-template-part-7-configuring-swagger-9b00ceb8a81f
Spring Boot 3 Template (Part 7) — Swagger | by Dwiki Witman | Medium
September 6, 2024 - This code is a configuration class for Swagger (OpenAPI) in a Spring Boot application. It’s used to customize the documentation and UI for your API.
🌐
Medium
apu-pradhan.medium.com › how-to-set-up-swagger-in-spring-boot-68b3fe862a0d
How to Set Up Swagger in Spring Boot | by Apu | Medium
November 18, 2024 - Spring Boot 3.x: Use SpringDoc version 2.x (e.g., springdoc-openapi-starter-webmvc-ui). Keeping the versions aligned ensures proper functionality of Swagger in your Spring Boot application. You can customize your Swagger UI paths using the following properties:
🌐
Keitaro
keitaro.com › insights › 2024 › 04 › 18 › implementing-swagger-in-springboot-applications
Keitaro – Implementing Swagger in SpringBoot applications
The content of the OpenApiConfig ... within a Spring Boot application. It encapsulates the essential configurations necessary for documentation creation. Parameters such as title, version, and description, meticulously defined within this class, will prominently feature in the Swagger interface. Having executed these vital configurations, it’s time to launch our project and navigate to http://localhost:8080/swagger-ui/index...
🌐
Javainuse
javainuse.com › spring › boot_swagger
Spring Boot + Swagger 2 Simple Hello World example
Now go to http://localhost:8080/swagger-ui.html. We will see the documentation for the exposed API as follows- Using the Try it button we can also check if the service is up. In the next post we see use of various swagger annotations using example ... See Also Spring Boot Hello World Application- Create simple controller and jsp view using Maven Spring Boot Hello World Application- Create simple controller and jsp view using Gradle Spring Boot Tutorial-Spring Data JPA Spring Boot + Simple Security Configuration Pagination using Spring Boot Simple Example Spring Boot + ActiveMQ Hello world Example Spring Boot + Swagger- Understanding the various Swagger Annotations Spring Boot Main Menu Spring Boot Interview Questions
🌐
Medium
medium.com › @AlexanderObregon › adding-swagger-ui-to-document-spring-boot-apis-67e6b42038d9
Adding Swagger UI to Document Spring Boot APIs | Medium
May 25, 2025 - Learn how to add Swagger UI to Spring Boot with Springdoc by generating live OpenAPI docs using annotations, metadata, and controller scanning.
Top answer
1 of 3
3

I had a similar task for Spring Boot 2.5.6 and springdoc-openapi-webflux-ui 1.5.12. I've found several possible solutions for myself. Maybe it will be helpful for somebody else.


Set springdoc.swagger-ui.path directly

The straightforward way is to set property springdoc.swagger-ui.path=/custom/path. It will work perfectly if you can hardcode swagger path in your application.


Override springdoc.swagger-ui.path property

You can change default swagger-ui path programmatically using ApplicationListener<ApplicationPreparedEvent>. The idea is simple - override springdoc.swagger-ui.path=/custom/path before your Spring Boot application starts.

@Component
public class SwaggerConfiguration implements ApplicationListener<ApplicationPreparedEvent> {

    @Override
    public void onApplicationEvent(final ApplicationPreparedEvent event) {
        ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
        Properties props = new Properties();
        props.put("springdoc.swagger-ui.path", swaggerPath());
        environment.getPropertySources()
                .addFirst(new PropertiesPropertySource("programmatically", props));
    }

    private String swaggerPath() {
        return "/swagger/path"; //todo: implement your logic here.
    }
}

In this case, you must register the listener before your application start:

@SpringBootApplication
@OpenAPIDefinition(info = @Info(title = "APIs", version = "0.0.1", description = "APIs v0.0.1"))
public class App {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(App.class);
        application.addListeners(new SwaggerConfiguration());
        application.run(args);
    }
}

Redirect using controller


You can also register your own controller and make a simple redirect (the same as what you suggest, but in my case, I need to use the WebFlux approach):

@RestController
public class SwaggerEndpoint {

    @GetMapping("/custom/path")
    public Mono<Void> api(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.PERMANENT_REDIRECT);
        response.getHeaders().setLocation(URI.create("/swagger-ui.html"));
        return response.setComplete();
    }
}

The problem with such an approach - your server will still respond if you call it by address "/swagger-ui.html".

2 of 3
2

Apparantly the library integrates natively only with spring-boot applications like you mentioned in your comment. If you want to use spring, it's possible but the integration details aren't documented, because it really depends on the version/module and the nature of you spring application.

You can check the FAQ to see if it answers your questions.

There are some more answers here on SO.

Top answer
1 of 1
4

To reproduce the issue, I:

  1. Started simple (maven,web,devtools)

  2. Added springdoc (for api-generation)

    <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
      <version>2.0.4</version>
    </dependency>
    
  3. Added (current) webjars-swagger-ui:

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>swagger-ui</artifactId>
      <version>4.18.1</version>
    </dependency>
    
  4. Deactivated springdoc's UI (application.properties):

    springdoc.swagger-ui.enabled=false
    
  5. Some rudimentary @RestController to generate my API at /v3/api-docs/..


Result

We get the "default" swagger UI at http://localhost:8080/webjars/swagger-ui/index.html (pointing to https://petstore.swagger.io API ...;( ##


(One possible) Fix/Workaround

Overwriting swagger initializer:

  1. Copy swagger-initalizer.js

    • from swagger-ui.<YOUR-VERSION>.jar!/META-INF/resources/webjars/swagger-ui/<YOUR-VERSION>/
    • to src/main/resources/META-INF/resources/webjars/swagger-ui/<YOUR-VERSION>/

    (This let's you customize (theoretically any) webjars file. Destination folder is important/may vary with time/spring versions)

  2. Modifying it:

    ...
    url: "/path/to/your/v2/api-docs"
    ...
    

    to your needs/suits.

That's it! (Running the application,) Swagger-ui will point to /path/to/your/v2/api-docs.


Alternative approaches can be:

  • to (appropriately) replace swagger-config.json
  • to use a custom html/resolver/initialiser

But still wondering, why doesn't/how the "url (configuration) approach" works (as documented)/since when it is "not allowed").

Thanks to & for more alternatives see also: Webjars - Add configuration to Swagger-UI webjar