java 生产忽略swagger注解
时间: 2025-01-02 20:36:40 浏览: 7
### 配置生产环境忽略Swagger注解
为了确保在生产环境中不启用Swagger文档生成功能,在Java项目中可以通过多种方式实现这一目标。一种常见的方式是在配置文件中通过条件判断来控制`@EnableSwagger2`或`@EnableOpenApi`注解的行为。
#### 方法一:基于Profile的配置
可以在启动类中利用Spring Profiles特性,仅当特定profile激活时才加载Swagger相关的配置:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
如果希望排除Swagger,则可以将其置于单独的configuration类并应用profiles属性[^1]:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@Profile("!prod") // 当不是prod profile时生效
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
```
这样做的好处是可以轻松切换不同环境下是否开启Swagger支持,只需更改运行时指定的active profiles即可。
#### 方法二:动态注册Bean
另一种方法是根据某些条件(比如系统属性或环境变量)决定是否向Spring容器注入Docket Bean实例。这种方式更加灵活,允许更复杂的逻辑判断[^2]。
```java
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.support.GenericApplicationContext;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
public class ConditionalSwaggerRegistrar implements ApplicationContextInitializer<GenericApplicationContext> {
private final boolean shouldRegister;
public ConditionalSwaggerRegistrar(boolean shouldRegister) {
this.shouldRegister = shouldRegister;
}
@Override
public void initialize(GenericApplicationContext context) {
if (shouldRegister) {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
ApiInfo apiInfo = new ApiInfoBuilder().version("1.0").title("API Title").description("").build();
Docket docket = new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo);
beanFactory.registerSingleton("swaggerDocket", docket);
}
}
}
```
此代码片段展示了如何依据传入参数`shouldRegister`来有条件地注册Swagger所需的bean对象。
阅读全文