SpringBoot学习二:整合Swagger UI

束飞捷
2023-12-01

现在比较推崇前后端分离的创建项目,前端使用诸如ReactVueAngular等前端框架,后端使用诸如微服务、Node等;因此,前后端的解耦和至关重要。那后端开发时如何查看开发效果呢?Swagger UI提供了解决方案。

下面简单记录一下,SpringBoot整合Swagger UI的方式。

  1. 加载Swagger的Maven配置文件
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.5.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.5.0</version>
</dependency>
复制代码
  1. 创建配置文件SwaggerConfig.java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("online.suiyu.springbootdemo.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger Title")
                .description("Swagger Description")
                .termsOfServiceUrl(" Swagger terms of service")
                .version("1.0.0")
                .build();
    }
}
复制代码
  1. 使用,在Controller中使用注解即可
@Api("测试类")
@RestController
@RequestMapping("index")
public class IndexController {
    @ApiOperation(value = "index", notes = "测试方法", tags = {"hello"})
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index() {
        return "Hello,World!";
    }
}
复制代码
  1. 运行项目,查看http://localhost:8080/swagger-ui.html即可看到API文档。

如果运行出错,可以查看项目结构:

关于注解的解释:github.com/swagger-api…

 类似资料: