在Debian系统下集成Swagger与Spring Boot,可以按照以下步骤进行:
首先,你需要创建一个Spring Boot项目。你可以使用Spring Initializr来快速生成项目结构。
com.example
swagger-demo
swagger-demo
Demo project for Swagger with Spring Boot
com.example.swaggerdemo
Jar
11
或 17
Spring Web
Springfox Swagger2
Springfox Swagger UI
Generate
下载项目压缩包。在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。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:Linux下Swagger与Spring Boot如何集成