Swagger在Java项目中的集成通常分为以下几个步骤:
- 添加依赖:在Spring Boot项目中,可以通过添加
springfox-swagger2
和springfox-swagger-ui
的依赖来实现Swagger的基本功能。
io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2
- 配置Swagger:在
application.yml
或application.properties
中配置Swagger的相关信息。
springfox: swagger: base-path: /api group-name: "example" info: version: "1.0" title: "Example API"
- 注解API:在控制器类中使用
@Api
、@ApiOperation
、@ApiParam
等注解来定义API的描述、参数和返回值。
@RestController @RequestMapping("/api") public class ExampleController { @GetMapping("/hello") @ApiOperation(value = "https://www.yisu.com/ask/返回示例信息", response = String.class) public String hello(@ApiParam(value = "https://www.yisu.com/ask/用户ID", required = true) @RequestParam Long userId) { return "Hello, " + userId; } }
- 启用Swagger UI:在主类中启用Swagger配置。
@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(); } }