在Ubuntu系统中,将Swagger与Spring Boot搭配使用可以帮助你为你的RESTful API创建交互式的API文档。以下是详细的步骤指南:
首先,你需要创建一个Spring Boot项目。你可以使用Spring Initializr(https://start.spring.io/)来快速生成项目结构。
将下载的ZIP文件解压到你的本地开发环境中,然后使用你喜欢的IDE(如IntelliJ IDEA, VSCode等)导入项目。
在你的pom.xml(如果你使用Maven)或build.gradle(如果你使用Gradle)文件中添加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>
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'io.springfox:springfox-swagger-ui:2.9.2'
创建一个配置类来启用Swagger。
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;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.yourpackage")) // 替换为你的包名
.paths(PathSelectors.any())
.build();
}
}
在终端中运行以下命令来启动Spring Boot应用:
./mvnw spring-boot:run
或者如果你使用的是Gradle:
./gradlew bootRun
打开浏览器并访问以下URL:
http://localhost:8080/swagger-ui.html
你应该能够看到Swagger UI界面,其中列出了你的所有API端点,并且可以进行交互式测试。
你可以进一步自定义Swagger UI,例如添加API信息、安全配置等。以下是一个简单的示例:
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Collections;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.yourpackage"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo(
"Your API Title",
"Description of your API",
"API TOS",
"Terms of service",
new Contact("Your Name", "www.example.com", "your.email@example.com"),
"License of API", "API license URL", Collections.emptyList());
}
}
通过以上步骤,你就可以在Ubuntu系统中成功地将Swagger与Spring Boot搭配使用,并创建交互式的API文档。