在Linux环境下,将Swagger与Spring Boot结合使用可以让你更方便地构建和测试RESTful API。以下是详细的步骤:
1. 添加依赖
首先,在你的Spring Boot项目的pom.xml文件中添加Swagger和Swagger UI的依赖。
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.9.2version>
dependency>
dependencies>
2. 配置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();
}
}
3. 启动Spring Boot应用
确保你的Spring Boot应用能够正常启动。你可以使用以下命令来启动应用:
./mvnw spring-boot:run
4. 访问Swagger UI
一旦应用启动,你可以通过浏览器访问Swagger UI界面。默认情况下,Swagger UI的地址是:
http://localhost:8080/swagger-ui.html
5. 配置Swagger UI(可选)
如果你想要自定义Swagger UI的外观或行为,可以在配置类中进行相应的设置。例如,你可以更改Swagger UI的主题颜色:
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 java.util.Collections;
@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()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo(
"My REST API",
"Some custom description of 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());
}
}
6. 测试API
在Swagger UI界面中,你可以看到你的API列表,并可以点击每个API来查看其详细信息和测试接口。
通过以上步骤,你就可以在Linux环境下将Swagger与Spring Boot结合使用,从而更方便地构建和测试RESTful API。
以上就是关于“Linux下Swagger如何与Spring Boot结合”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm