再详细些
时间: 2023-12-20 15:14:34 浏览: 32
好的,以下是更详细的步骤:
1. 针对整个应用禁用 Swagger
第一种方法是在应用的 `application.properties` 文件中添加以下配置:
```properties
springfox.documentation.enabled=false
```
这样,Swagger 将不会生成文档,并且 Swagger UI 也将无法访问。
第二种方法是在应用的启动类上添加 `@EnableSwagger2` 注解,并重写 `addResourceHandlers` 方法,将 Swagger UI 的访问路径重定向到 `/error`:
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/")
.setCachePeriod(0);
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(0);
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.setCachePeriod(0);
registry.addResourceHandler("/swagger-resources/**")
.addResourceLocations("classpath:/META-INF/swagger-resources/")
.setCachePeriod(0);
}
}
```
在上面的代码中,我们通过重写 `addResourceHandlers` 方法,将 Swagger UI 相关的资源路径映射到 `/error`,这样访问 Swagger UI 时将会返回 404 错误。
2. 针对指定的 API 禁用 Swagger
如果你只想禁止 Swagger 记录某些 API,可以在其实现类上添加 `@ApiIgnore` 注解,例如:
```java
@RestController
@RequestMapping("/api")
@ApiIgnore
public class MyController {
// ...
}
```
这样,Swagger 将不会在文档中显示该 API。
另外,如果你使用的是 Swagger 3.x 版本,`@EnableSwagger2` 注解将无法使用,需要改为 `@EnableSwagger2WebMvc` 注解。同时,Swagger UI 的访问路径也发生了变化,应该将 `addResourceHandlers` 方法中的 `/swagger-ui.html` 改为 `/swagger-ui/index.html`。