在CentOS上配置Swagger,通常是為了給Spring Boot應用程序提供一個API文檔界面。以下是配置Swagger的基本步驟:
添加Swagger依賴:
在你的Spring Boot項目的pom.xml
文件中添加Swagger的依賴。例如,使用Springfox Swagger 2,你可以添加以下依賴:
<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>
請注意,版本號可能會更新,所以請檢查最新的版本。
配置Swagger: 創建一個Java類來配置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;
@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();
}
}
訪問Swagger UI:
啟動你的Spring Boot應用程序后,你可以通過瀏覽器訪問Swagger UI界面。默認情況下,URL是http://<your-server-address>:<port>/swagger-ui.html
。
配置安全設置(可選): 如果你的應用程序有安全設置,比如使用了Spring Security,你需要確保Swagger UI的URL不會被安全設置攔截。例如,你可以在Spring Security配置中添加以下代碼:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**");
}
自定義Swagger UI(可選): 你可以通過添加更多的配置來自定義Swagger UI的外觀和行為。例如,你可以設置API信息、聯系信息、許可等。
請確保你的Spring Boot版本與Swagger依賴版本兼容。如果你使用的是Spring Boot 3.x,你可能需要使用Springfox的替代品,如SpringDoc OpenAPI,因為Springfox 3.0.0不支持Spring Boot 3.x。