在CentOS系统上集成Swagger与Spring Boot,可以按照以下步骤进行:
首先,你需要创建一个Spring Boot项目。你可以使用Spring Initializr(https://start.spring.io/)来快速生成项目结构。
Spring Web
和 Springfox Swagger2
(用于Swagger 2.x)或者 Springdoc OpenAPI
(用于OpenAPI 3.x)。如果你选择使用Swagger 2.x,可以在pom.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>
如果你选择使用OpenAPI 3.x,可以在pom.xml
中添加以下依赖:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.2</version>
</dependency>
创建一个配置类来配置Swagger:
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();
}
}
Springdoc OpenAPI会自动配置Swagger UI,你只需要在application.properties
或application.yml
中进行一些基本配置:
springdoc.api-docs.path=/v3/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
启动你的Spring Boot应用,然后访问以下URL来查看Swagger UI:
http://localhost:8080/swagger-ui.html
http://localhost:8080/swagger-ui/index.html
在你的控制器类和方法上添加Swagger注解,以便生成详细的API文档。例如:
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/api")
@Api(tags = "示例控制器")
public class ExampleController {
@GetMapping("/hello")
@ApiOperation("返回一个简单的问候语")
public String sayHello() {
return "Hello, World!";
}
}
将你的Spring Boot应用打包成JAR文件,并上传到CentOS服务器。你可以使用以下命令来打包和运行应用:
# 打包应用
mvn clean package
# 上传JAR文件到CentOS服务器
scp target/your-application.jar user@centos-server:/path/to/deploy
# 在CentOS服务器上运行应用
ssh user@centos-server
cd /path/to/deploy
java -jar your-application.jar
现在,你的Spring Boot应用应该在CentOS服务器上运行,并且可以通过浏览器访问Swagger UI来查看和测试API文档。