在Ubuntu环境下将Swagger集成到Spring Boot项目中,可以按照以下步骤进行操作:
如果你还没有一个Spring Boot项目,可以使用Spring Initializr来创建一个。
com.example
。swagger-demo
。swagger-demo
。com.example.swaggerdemo
。Jar
或 War
。11
或 17
。Dependencies
部分添加 Spring Web
和 Springfox Swagger2
。Generate
下载项目压缩包。在你的 pom.xml
文件中添加以下依赖:
<dependencies>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Springfox Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- Springfox Swagger UI -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
创建一个配置类来配置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.swaggerdemo.controller"))
.paths(PathSelectors.any())
.build();
}
}
创建一个简单的Controller来测试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应用:
./mvnw spring-boot:run
打开浏览器并访问以下URL来查看Swagger UI:
http://localhost:8080/swagger-ui.html
你应该能够看到你的API文档和测试界面。
通过以上步骤,你已经成功地在Ubuntu环境下将Swagger集成到了Spring Boot项目中。你可以根据需要进一步配置Swagger,例如添加更多的API文档、自定义Swagger UI等。