在Linux环境下,将Swagger与Spring Boot结合使用可以让你更方便地构建和测试RESTful API。以下是详细的步骤指南:
1. 创建Spring Boot项目
首先,你需要创建一个Spring Boot项目。你可以使用Spring Initializr(https://start.spring.io/)来快速生成项目结构。
- 访问Spring Initializr网站。
- 选择项目元数据(如Group、Artifact等)。
- 添加依赖项:选择
Spring Web和Springfox Swagger2(或Springdoc OpenAPI,后者更现代且易于使用)。 - 点击“Generate”下载项目压缩包。
2. 解压并导入项目
解压下载的项目压缩包,并使用你喜欢的IDE(如IntelliJ IDEA、Eclipse等)导入项目。
3. 配置Swagger
使用Springfox Swagger2
-
添加依赖: 在
pom.xml文件中添加以下依赖:<dependency> <groupId>io.springfoxgroupId> <artifactId>springfox-swagger2artifactId> <version>2.9.2version> dependency> <dependency> <groupId>io.springfoxgroupId> <artifactId>springfox-swagger-uiartifactId> <version>2.9.2version> dependency> -
配置Swagger: 创建一个配置类来配置Swagger:
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.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build(); } } -
访问Swagger UI: 启动Spring Boot应用程序后,访问
http://localhost:8080/swagger-ui.html即可看到Swagger UI界面。
使用Springdoc OpenAPI
-
添加依赖: 在
pom.xml文件中添加以下依赖:<dependency> <groupId>org.springdocgroupId> <artifactId>springdoc-openapi-uiartifactId> <version>1.5.2version> dependency> -
配置OpenAPI: Springdoc OpenAPI会自动配置Swagger UI,无需额外配置。
-
访问OpenAPI UI: 启动Spring Boot应用程序后,访问
http://localhost:8080/swagger-ui/index.html即可看到OpenAPI UI界面。
4. 编写Controller
编写一个简单的Controller来测试Swagger:
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 = "示例接口")
public class ExampleController {
@GetMapping("/hello")
@ApiOperation("返回Hello World")
public String hello() {
return "Hello World";
}
}
5. 启动应用程序
在终端中运行以下命令启动Spring Boot应用程序:
./mvnw spring-boot:run
6. 测试API
打开浏览器,访问http://localhost:8080/swagger-ui.html(或http://localhost:8080/swagger-ui/index.html),你应该能看到Swagger UI界面,并且可以测试你的API。
通过以上步骤,你就可以在Linux环境下成功地将Swagger与Spring Boot结合使用,从而更方便地构建和测试RESTful API。
以上就是关于“Linux中Swagger与Spring Boot如何结合”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm