生产环境禁用Swagger

1. 打包环境的属性值来禁用

1.1 在属性文件中配置变量

#Swagger开关
SWAGGER.ENABLE = true

1.2 在配置类中设置开关


    @Value("${SWAGGER.ENABLE}")
    private boolean swaggerEnable;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (swaggerEnable) {
            System.out.println(swaggerEnable);
            registry.addResourceHandler("swagger-ui.html")
                    .addResourceLocations("classpath:/META-INF/resources/");

            registry.addResourceHandler("/webjars/**")
                    .addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }

2. 打包环境 使用@Profile注解

项目背景介绍, 我们有三个环境dev,test,prod,我们只在dev环境中使用swagger,test和prod都禁止使用

2.1 添加@Profile注解

@EnableSwagger2
@Profile("dev")
public class Swagger2 extends WebMvcConfigurationSupport {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.yq.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot 测试使用 Swagger2 构建RESTful API")
                .contact(new Contact("EricYang", "https://github.com/yqbjtu/springbootJpa.git", "test@163.com"))
                .version("1.0")
                .description("User API 描述")
                .build();
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
    }
}

2.2 开发环境

开发环境,启用Swagger

mvn package -P dev
  •  

启动后可以看到swagger可以正常访问。

2.3 生产环境

禁用Swagger

mvc package -P prod
  •  

将代码编译打包,启动后不能访问swagger

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值