在Debian系统上将Swagger与Spring Boot结合使用,可以按照以下步骤进行:
首先,你需要创建一个Spring Boot项目。你可以使用Spring Initializr(https://start.spring.io/)来快速生成项目结构。
在你的pom.xml文件中添加Swagger和Swagger UI的依赖:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- Swagger UI -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
创建一个配置类来配置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")) // 替换为你的包名
.paths(PathSelectors.any())
.build();
}
}
在你的主应用类上添加@SpringBootApplication注解,并启动应用:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
启动应用后,打开浏览器并访问以下URL来查看Swagger UI:
http://localhost:8080/swagger-ui.html
在你的控制器类中使用Swagger注解来编写API文档:
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
@Api(tags = "示例控制器")
public class ExampleController {
@GetMapping("/hello")
@ApiOperation("返回一个简单的问候信息")
public String hello() {
return "Hello, World!";
}
}
每次修改API后,Swagger会自动更新文档。你可以重新访问http://localhost:8080/swagger-ui.html来查看最新的API文档。
通过以上步骤,你就可以在Debian系统上成功地将Swagger与Spring Boot结合使用了。