在Linux环境中,将Swagger与Spring Boot集成可以帮助你创建、测试和文档化你的RESTful API。以下是集成Swagger与Spring Boot的步骤:
首先,在你的pom.xml
(如果你使用Maven)或build.gradle
(如果你使用Gradle)文件中添加Swagger和Springfox的依赖。
在你的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>
在你的build.gradle
文件中添加以下依赖:
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'io.springfox:springfox-swagger-ui:2.9.2'
创建一个配置类来配置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.yourpackage.controller"))
.paths(PathSelectors.any())
.build();
}
}
在这个配置中,RequestHandlerSelectors.basePackage("com.yourpackage.controller")
指定了你的控制器所在的包。
确保你的Spring Boot应用已经启动。你可以使用以下命令来启动你的应用:
./mvnw spring-boot:run
或者如果你使用的是Gradle:
./gradlew bootRun
一旦你的应用启动,你可以通过浏览器访问Swagger UI。默认情况下,Swagger UI的地址是:
http://localhost:8080/swagger-ui.html
在这里,你可以查看和测试你的API。
你可以进一步自定义Swagger UI,例如添加认证、自定义样式等。以下是一个简单的示例,展示如何添加基本认证:
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.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.yourpackage.controller"))
.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());
}
}
通过这些步骤,你应该能够在Linux环境中成功集成Swagger与Spring Boot,并使用Swagger UI来测试和文档化你的API。