Springboot线上环境彻底关闭Swagger-UI

时间:2025-03-20 19:18:02

文章目录

    • 概要
    • 整体架构流程
    • 技术细节
    • 小结

概要

Springboot线上环境彻底关闭Swagger-UI

整体架构流程

使用@Profile排除线上环境其他环境生效
2.创建一个控制类使用@Profile仅线上环境生效,使访问返回404

技术细节

/**
 * @author: suitman
 * @description: go fucking comment....
 * @create: 2021-02-07 10:43
 **/
@Configuration
@EnableSwagger2
@Profile("!prod")
public class SwaggerConfig implements WebMvcConfigurer {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        // 设置标题
                        .title("****")
                        // 描述
                        .description("***")
                        // 作者信息
                        .contact(new Contact("***", null, null))
                        // 版本
                        .version("版本号: 1")
                        .build())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build();
    }

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

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
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.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Profile("prod")
@RestController
@Slf4j
public class DisableSwaggerUiController {

    @RequestMapping(value = "", method = RequestMethod.GET)
    public void getSwagger(HttpServletResponse httpResponse) throws IOException {
        httpResponse.setStatus(HttpStatus.NOT_FOUND.value());
    }
}

小结

通过这种方式可以彻底关闭线上环境访问直接返回404