在CentOS环境下,将Swagger与Spring Boot进行联调需要遵循以下步骤:
确保你的CentOS系统已经安装了Java和Maven。如果没有安装,可以使用以下命令进行安装:
sudo yum install java-1.8.0-openjdk-devel
sudo yum install maven
你可以使用Spring Initializr来创建一个新的Spring Boot项目。访问https://start.spring.io/,选择所需的依赖项(如Spring Web),然后生成项目并下载到本地。
在你的Spring Boot项目的pom.xml文件中添加Swagger依赖:
<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:
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:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Swagger!";
}
}
在项目根目录下运行以下命令来启动Spring Boot应用:
mvn spring-boot:run
打开浏览器,访问http://<your-server-ip>:<port>/swagger-ui.html,其中<your-server-ip>是你的CentOS服务器的IP地址,<port>是Spring Boot应用的端口号(默认是8080)。
如果Swagger UI没有正确显示,可以检查以下几点:
通过以上步骤,你应该能够在CentOS环境下成功地将Swagger与Spring Boot进行联调。