EnableSwagger2 类 怎么引入
时间: 2024-10-12 17:09:44 浏览: 16
`EnableSwagger2` 是 Springfox 框架中的一个注解,用于启用 Swagger 2.x 的文档生成功能。Springfox 是一个强大的 API 文档生成工具,它与 Spring Boot 结合非常好。
要在项目中引入 `EnableSwagger2`,你需要做以下几个步骤:
1. 添加依赖:首先,在你的 Maven 或 Gradle 项目的构建文件中添加 springfox-swagger2 和 springfox-ui 的依赖。例如对于 Maven,可以在 `pom.xml` 中加入:
```xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0-M5</version> <!-- 使用最新稳定版本 -->
</dependency>
```
2. 配置扫描路径:通过 `@EnableSwagger2` 注解标记某个配置类,指定需要扫描哪些类以查找 Swagger 注解,比如:
```java
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private static final String SWAGGER_API_TITLE = "Your Application API";
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.your.package")) // 替换为实际的包名
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(SWAGGER_API_TITLE)
.description("Your API description")
.contact(new Contact("Your Name", "your-url.com", "your-email@example.com"))
.license("Apache 2.0")
.build();
}
}
```
这里 `createRestApi` 方法中的 `.apis(RequestHandlerSelectors.basePackage(...))` 指定了基于哪个包下的控制器去创建 Swagger 文档。
3. 启动 Swagger UI:通常,Swagger UI 默认会提供一个端点供你访问 API 文档,不需要额外配置。如果需要自定义,可以查看 Springfox 文档关于如何集成前端 UI。
阅读全文
相关推荐


















