在Debian系統下集成Swagger與Spring Boot,可以按照以下步驟進行:
首先,你需要創建一個Spring Boot項目。你可以使用Spring Initializr來快速生成項目結構。
com.exampleswagger-demoswagger-demoDemo project for Swagger with Spring Bootcom.example.swaggerdemoJar11 或 17Spring WebSpringfox Swagger2Springfox Swagger UIGenerate 下載項目壓縮包。在Spring Boot項目中配置Swagger,需要創建一個配置類。
src/main/java/com/example/swaggerdemo 目錄下創建一個新的Java類,例如 SwaggerConfig.java。package com.example.swaggerdemo;
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.swaggerdemo.controller"))
.paths(PathSelectors.any())
.build();
}
}
創建一個簡單的控制器來測試Swagger。
src/main/java/com/example/swaggerdemo/controller 目錄下創建一個新的Java類,例如 HelloController.java。package com.example.swaggerdemo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Swagger!";
}
}
在終端中運行Spring Boot應用程序。
cd /path/to/swagger-demo
./mvnw spring-boot:run
打開瀏覽器并訪問以下URL:
http://localhost:8080/swagger-ui.html
你應該能夠看到Swagger UI界面,并且可以看到你創建的API文檔。
如果你有安全設置(例如Spring Security),你可能需要配置Swagger UI的訪問權限。
SecurityConfig.java 中添加以下代碼:package com.example.swaggerdemo;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/swagger-ui.html", "/webjars/**", "/swagger-resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}
這樣,Swagger UI和相關的靜態資源就可以被公開訪問了。
通過以上步驟,你就可以在Debian系統下成功集成Swagger與Spring Boot。