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

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

方法一:application.properties 或 application.yml

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

springfox.documentation.swagger.v2.enabled: false

这将禁用 Swagger 的自动配置。

方法二:使用条件注解

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

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

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

swagger.enabled: false

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

方法三:使用 Profile

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

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

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

方法四:使用 exclude 属性

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

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

方法五:使用enable属性

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(false)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.ls.uem.emer.command.server.rest"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("xxxxx接口文档")
                        .description("xxxxxx接口文档,详细信息......")
                        .version("9.0")
                        .build());
    }
}

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

posted @ 2024-01-02 16:15  夏威夷8080  阅读(2792)  评论(0编辑  收藏  举报