Swagger與Ubuntu可以協同工作,主要用于API文檔的生成和測試。Swagger是一個工具集,包括Swagger Editor和Swagger UI,它們可以幫助開發者設計、構建、文檔化和使用RESTful web服務。Ubuntu是一個流行的Linux發行版,提供了穩定的環境和豐富的軟件包管理工具。
sudo apt update
sudo apt install -y nodejs npm
wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v3.48.0.tar.gztar -xvf v3.48.0.tar.gz
cd swagger-ui-3.48.0
npm install
npm install -g http-server
http-server -p 8081
之后可以在瀏覽器中訪問 http://localhost:8081 來使用Swagger UI。
sudo apt update
sudo apt install docker.io
docker pull swaggerapi/swagger-ui-express
docker run -p 8080:8080 swaggerapi/swagger-ui-express
之后可以在瀏覽器中訪問 http://localhost:8080 來使用Swagger UI。
創建Spring Boot項目: 使用Spring Initializr創建一個新的Spring Boot項目,并添加Spring Web和Springfox Swagger2依賴。
添加Swagger依賴:
在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>
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();
}
}
./mvnw spring-boot:run
通過以上步驟,你可以在Ubuntu上成功地將Swagger集成到Spring Boot項目中,并進行API文檔的生成和測試。