How to change basePath for Springfox Swagger 2.0

前端 未结 3 1635
Happy的楠姐
Happy的楠姐 2021-02-05 03:16

I\'m running a service, where Swagger UI is accessible at:

http://serviceURL/swagger-ui.html

However, it is behind a proxy, such as:

         


        
3条回答
  •  無奈伤痛
    2021-02-05 03:45

    Using spring fox 2.9.2, using solution mentioned by other users is not works.

    What is not working:

    • Overriding getApplicationBasePath on Docket pathProvider
    • Adding server.servlet.context-path=/serviceName

    I don't know why they are not work, but in my project that using Springboot 2.1.6.RELEASE and Spring 5.1.8.RELEASE, the two solution above is being ignored.

    So, I am trying another approach: https://github.com/springfox/springfox/issues/2817#issuecomment-517753110

    According to the github issue comment, I need to override Springfox json serialize class and thank god this works. Here is the code example:

    import io.swagger.models.Swagger;
    import org.springframework.context.annotation.Primary;
    import org.springframework.core.env.Environment;
    import org.springframework.stereotype.Component;
    import springfox.documentation.spring.web.json.JacksonModuleRegistrar;
    import springfox.documentation.spring.web.json.Json;
    import springfox.documentation.spring.web.json.JsonSerializer;
    
    import java.util.Arrays;
    import java.util.List;
    
    import static io.github.jhipster.config.JHipsterConstants.SPRING_PROFILE_PRODUCTION;
    
    @Component
    @Primary
    public class CustomBasePathSerialize extends JsonSerializer {
    
        // this injection is optional, if you don't need to
        // add basePath based on active profile, remove this.
        private final Environment env;
    
        public CustomBasePathSerialize(List modules,
                                       Environment env) {
            super(modules);
            this.env = env;
        }
    
        @Override
        public Json toJson(Object toSerialize) {
            if (toSerialize instanceof Swagger) {
                Swagger swagger = (Swagger) toSerialize;
                String basePath = "/serviceName";
                List profiles = Arrays.asList(env.getActiveProfiles());
    
                // OPTIONAL: you can change basePath if you have difference path 
                // on any Spring profile, for example prod:
                if (profiles.contains(SPRING_PROFILE_PRODUCTION)) {
                    basePath = "/";
                }
                swagger.basePath(basePath);
            }
            return super.toJson(toSerialize);
        }
    }
    

提交回复
热议问题