Spring Boot + Swagger + custom swagger-ui.html

后端 未结 2 1285
情书的邮戳
情书的邮戳 2021-02-19 22:11

I\'ve got problems migrating a war application to a spring boot jar application.

I\'m using spring boot 1.4.1 and swagger 2.6.0.

To customize swagger ui in a war

2条回答
  •  清酒与你
    2021-02-19 22:36

    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:

    
    

    with this line:

    
    

    This is my api.html

    
    
    
        
        Swagger UI
        
        
        
        
        
        
        
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    
        
    
    
    
    
    
    
     

    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 = $('')
                        .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

提交回复
热议问题