在Linux中集成Swagger与Spring Boot的步骤如下:
首先,在Spring Boot项目的pom.xml
文件中添加Swagger和Swagger UI的依赖。对于Spring Boot 2.x,可以使用springfox-swagger2
和springfox-swagger-ui
这两个库。
Maven依赖示例:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
</dependencies>
创建一个Java类来配置Swagger。这个类需要使用@Configuration
注解,并且包含一个方法来定义Swagger的Docket
Bean。
SwaggerConfig.java示例:
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();
}
}
使用Maven命令来构建和运行Spring Boot应用程序:
./mvnw spring-boot:run
确保你有适当的权限来执行这个命令,可能需要使用sudo
。
在浏览器中访问以下URL查看Swagger UI界面:
http://localhost:8080/swagger-ui.html
这里的端口号8080
是Spring Boot应用程序的默认端口,如果你的应用程序运行在不同的端口上,请相应地更改URL。
在控制器类和方法上添加Swagger注解,生成更详细的API文档。例如:
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("返回一个简单的问候语")
public String sayHello() {
return "Hello, World!";
}
}
修改控制器或方法后,Swagger会自动更新API文档。您可以随时访问Swagger UI界面查看最新文档。
通过以上步骤,您就可以在Linux环境中成功集成Swagger与Spring Boot,并且可以通过Swagger UI界面来查看和测试您的API。