Swagger是一种API文档生成工具,它可以与多种框架协同工作,以便为开发者提供方便、统一的API文档和测试界面。以下是Swagger与Spring Boot框架集成的方法:
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.5</version>
</dependency>
@EnableSwagger2
注解启用Swagger,并定义API文档的相关配置。@Configuration
@EnableSwagger2
public class MySwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
@Controller
@RequestMapping("/api")
public class ApiController {
@ApiOperation(value = "测试专用")
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
public String test() {
return "123";
}
}
http://localhost:8080/swagger-ui.html
来查看和测试API文档。以上步骤展示了如何在Spring Boot应用中集成Swagger,使得API文档的生成和测试变得简单快捷。通过这种方式,开发者可以在不离开开发环境的情况下,实时地看到API文档的更新,从而提高开发效率。