在Ubuntu上集成Swagger主要分为以下几个步骤:
1. 添加依赖
首先,你需要在项目的pom.xml
文件中添加springfox-swagger2
和springfox-swagger-ui
这两个依赖。例如:
io.springfox springfox-swagger2 YOUR_DESIRED_VERSION io.springfox springfox-swagger-ui YOUR_DESIRED_VERSION
将YOUR_DESIRED_VERSION
替换为实际使用的版本号。
2. 配置Swagger
接下来,创建一个配置类来启用Swagger并定义一些基本信息。例如,对于Spring Boot项目,你可以使用以下代码:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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 api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } }
这个配置类启用了Swagger,并告诉Swagger扫描所有的API接口来生成文档。
3. 访问Swagger UI
启动Spring Boot项目后,访问http://localhost:8080/swagger-ui.html
(假设服务端口为8080),你应该能够看到Swagger UI界面,其中列出了你的所有API端点。
4. 使用注解描述API
使用Swagger提供的注解来描述API的详细信息。例如:
import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Api(tags = "Sample API") public class SampleController { @ApiOperation(value = "https://www.yisu.com/ask/Get sample data") public CommonResponse getSampleData() { // Your implementation here } }
5. (可选)使用springdoc-openapi
集成Swagger UI
对于Spring Boot 3.x项目,你还可以使用springdoc-openapi
来集成Swagger UI,它提供了更简洁的配置方式。首先,添加springdoc-openapi-starter-webmvc-ui
依赖到你的pom.xml
:
org.springdoc springdoc-openapi-starter-webmvc-ui 2.8.5
然后,在application.yml
中进行简单配置:
springdoc: api-docs: path: /v3/api-docs swagger-ui: path: /dev-tools/
这样,你就可以通过访问http://localhost:8080/dev-tools/swagger-ui.html
来查看Swagger UI。
以上步骤应该能够帮助你在Ubuntu上成功集成Swagger。如果在集成过程中遇到问题,可以参考相关的官方文档或社区论坛寻求帮助。