springboot2整合swagger
时间: 2025-02-25 12:28:00 浏览: 47
### 如何在 Spring Boot 2 中整合 Swagger
#### 添加依赖项
为了使Swagger能够顺利运行于Spring Boot环境中,需向`pom.xml`文件中加入特定的Maven依赖。这些依赖允许开发者利用Swagger的功能来增强API文档的质量和交互体验[^1]。
```xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
```
#### 启用 Swagger 支持
要在应用程序内激活Swagger的支持,在主应用类上添加`@EnableSwagger2Doc`注解是一种方法;另一种常见的方式是在配置类里使用`@EnableSwagger2`并定义Docket Bean以定制化API文档的信息展示逻辑[^3][^4]。
```java
@SpringBootApplication
@EnableSwagger2Doc
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
```
对于更详细的自定义设置,则可以通过创建一个名为`SwaggerConfig`的Java配置类实现:
```java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot Demo中使用Swagger2构建RESTful APIs")
.version("1.0.0")
.build();
}
}
```
上述代码片段展示了如何通过指定包路径以及选择所有路径的方式来筛选需要被记录下来的API端点,并设置了API文档的基础信息如标题与版本号等属性[^4]。
阅读全文
相关推荐


















