swagger在生产环境中禁用

  • 问题

    • 最近在项目上遇到要在生产环境下禁用swagger的问题,找到两种解决办法,另一种在我的
  • 解决方案

    • 经过一番寻觅,发现了Spring boot中有个注解@ConditionalOnProperty,这个注解能够控制某个configuration是否生效。具体操作是通过其两个属性name以及havingValue来实现的,其中name用来从application.properties中读取某个属性值,如果该值为空,则返回false;如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。如果返回值为false,则该configuration不生效;为true则生效。
  • 代码

    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.ParameterBuilder;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.schema.ModelRef;
    import springfox.documentation.service.Parameter;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    import java.util.ArrayList;
    import java.util.List;
     
    @Configuration
    @ConditionalOnProperty(prefix = "swagger2",value = {"enable"},havingValue = "true")
    @EnableSwagger2
    public class SwaggerConfiguration {
     
      @Bean
      public Docket swagger(){
        return new Docket(DocumentationType.SWAGGER_2)
            .groupName("default")
            .apiInfo(new ApiInfoBuilder().title("SSP School API").version("1.0.0").build())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.pobo.pbsimu.opcontest.controller"))
            .build()
            .globalOperationParameters(globalOperationParameters());
      }
     
     
      private List<Parameter> globalOperationParameters(){
        List<Parameter> parameters = new ArrayList<>();
        parameters.add(new ParameterBuilder().name("ACCESS-TOKEN").description("ACCESS-TOKEN").required(false).parameterType("header").modelRef(new ModelRef("string")).build());
        return parameters;
      
      }
      
    }

猜你喜欢

转载自blog.csdn.net/qq_40006446/article/details/80323140