Spring Boot 项目中禁用 Swagger方法总结

发布时间 2024-01-02 16:17:49作者: 夏威夷8080

如果你想在Spring Boot 项目中禁用 Swagger,有几种可能的方法。以下是一些建议:

### 方法一:application.properties 或 application.yml

在`application.properties`或`application.yml`文件中添加以下配置:

```yaml
springfox.documentation.swagger.v2.enabled: false
```

这将禁用 Swagger 的自动配置。

### 方法二:使用条件注解

修改你的`SwaggerConfig`类,使用条件注解来控制是否启用 Swagger。例如:

```java
@Configuration
@ConditionalOnProperty(name = "swagger.enabled", havingValue = "true", matchIfMissing = true)
@EnableSwagger2
public class SwaggerConfig {
// Swagger配置代码
}
```

在`application.properties`或`application.yml`中添加如下配置:

```yaml
swagger.enabled: false
```

这样做将根据配置来决定是否启用 Swagger。

### 方法三:使用 Profile

在`SwaggerConfig`类中添加`@Profile`注解:

```java
@Configuration
@EnableSwagger2
@Profile("!production")
public class SwaggerConfig {
// Swagger配置代码
}
```

在生产环境中,不激活该配置文件。

### 方法四:使用 exclude 属性

在你的`@SpringBootApplication`注解上使用`exclude`属性排除`SwaggerConfig`:

```java
@SpringBootApplication(exclude = SwaggerConfig.class)
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
```

以上方法中,你可以选择最适合你项目的一种或组合使用。