srpingboot 集成swagger2 knife4j 具体的demo
时间: 2024-04-19 16:27:42 浏览: 98
以下是一个使用Spring Boot集成Swagger2和Knife4j的示例:
首先,在`pom.xml`文件中添加以下依赖项:
```xml
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- Swagger UI -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- Knife4j -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
```
接下来,在Spring Boot的启动类中加上Swagger2和Knife4j的相关注解。示例中的启动类为`DemoApplication.java`:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Demo API")
.description("API documentation for demo project")
.version("1.0")
.build();
}
}
```
在上述代码中,我们通过`@EnableSwagger2`注解启用Swagger2,并创建了一个`Docket` bean来配置Swagger2的基本信息。
接下来,在控制器类中使用Swagger2的注解来定义API文档。示例中的控制器类为`DemoController.java`:
```java
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
@Api(tags = "Demo API")
public class DemoController {
@GetMapping("/hello")
@ApiOperation(value = "Say hello", notes = "Returns a greeting message")
public String sayHello() {
return "Hello, Swagger!";
}
}
```
在上述代码中,我们使用了Swagger2的注解`@Api`和`@ApiOperation`来定义API的标签、描述和操作。
最后,运行Spring Boot应用程序,并访问`http://localhost:8080/doc.html`即可查看生成的API文档。你将看到Swagger2和Knife4j提供的界面,展示了API的详细信息。
这就是一个简单的Spring Boot集成Swagger2和Knife4j的示例。你可以根据实际需求进行配置和扩展。希望对你有所帮助!
阅读全文