在Linux环境下,将Swagger与Spring Boot结合使用可以让你更方便地构建和测试RESTful API。以下是详细的步骤指南:
首先,你需要创建一个Spring Boot项目。你可以使用Spring Initializr(https://start.spring.io/)来快速生成项目结构。
Spring Web和Springfox Swagger2(或Springdoc OpenAPI,后者更现代且易于使用)。解压下载的项目压缩包,并使用你喜欢的IDE(如IntelliJ IDEA、Eclipse等)导入项目。
添加依赖:
在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>
配置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界面。
添加依赖:
在pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.2</version>
</dependency>
配置OpenAPI: Springdoc OpenAPI会自动配置Swagger UI,无需额外配置。
访问OpenAPI UI:
启动Spring Boot应用程序后,访问http://localhost:8080/swagger-ui/index.html即可看到OpenAPI UI界面。
编写一个简单的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";
}
}
在终端中运行以下命令启动Spring Boot应用程序:
./mvnw spring-boot:run
打开浏览器,访问http://localhost:8080/swagger-ui.html(或http://localhost:8080/swagger-ui/index.html),你应该能看到Swagger UI界面,并且可以测试你的API。
通过以上步骤,你就可以在Linux环境下成功地将Swagger与Spring Boot结合使用,从而更方便地构建和测试RESTful API。