Swagger在Java项目中的集成通常分为以下几个步骤:
springfox-swagger2
和springfox-swagger-ui
的依赖来实现Swagger的基本功能。<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>
application.yml
或application.properties
中配置Swagger的相关信息。springfox:
swagger:
base-path: /api
group-name: "example"
info:
version: "1.0"
title: "Example API"
@Api
、@ApiOperation
、@ApiParam
等注解来定义API的描述、参数和返回值。@RestController
@RequestMapping("/api")
public class ExampleController {
@GetMapping("/hello")
@ApiOperation(value = "返回示例信息", response = String.class)
public String hello(@ApiParam(value = "用户ID", required = true) @RequestParam Long userId) {
return "Hello, " + userId;
}
}
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example"))
.paths(PathSelectors.any())
.build();
}
}