文章目录
概要
Springboot线上环境彻底关闭Swagger-UI
整体架构流程
1.SwaggerConfig使用@Profile排除线上环境其他环境生效
2.创建一个控制类使用@Profile仅线上环境生效,使访问swagger-ui.html返回404
技术细节
/**
* @author: suitman
* @description: go fucking comment....
* @create: 2021-02-07 10:43
**/@Configuration@EnableSwagger2@Profile("!prod")publicclassSwaggerConfigimplementsWebMvcConfigurer{@BeanpublicDocketcreateRestApi(){returnnewDocket(DocumentationType.SWAGGER_2).apiInfo(newApiInfoBuilder()// 设置标题.title("****")// 描述.description("***")// 作者信息.contact(newContact("***",null,null))// 版本.version("版本号: 1").build()).select().apis(RequestHandlerSelectors.withClassAnnotation(Api.class)).paths(PathSelectors.any()).build();}@OverridepublicvoidaddResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");}}
importlombok.extern.slf4j.Slf4j;importorg.springframework.context.annotation.Profile;importorg.springframework.http.HttpStatus;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.RestController;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;@Profile("prod")@RestController@Slf4jpublicclassDisableSwaggerUiController{@RequestMapping(value ="swagger-ui.html", method =RequestMethod.GET)publicvoidgetSwagger(HttpServletResponse httpResponse)throwsIOException{
httpResponse.setStatus(HttpStatus.NOT_FOUND.value());}}
小结
通过这种方式可以彻底关闭线上环境访问swagger-ui.html直接返回404
版权归原作者 阳夏丨 所有, 如有侵权,请联系我们删除。