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") 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("/swagger-ui.html").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 = "swagger-ui.html", method = RequestMethod.GET) public void getSwagger(HttpServletResponse httpResponse) throws IOException { httpResponse.setStatus(HttpStatus.NOT_FOUND.value()); } }
通过这种方式可以彻底关闭线上环境访问swagger-ui.html直接返回404