Swagger UI引入

乐正镜
2023-12-01

        Swagger是一个Restful风格接口的文档在线自动生成和测试的框架(http://swagger.io),Swagger UI可以自动生成接口文档,不需要频繁更新接口文档,保证接口文档与代码的一致,代码改动时,接口文档可以自动修改。

1、添加依赖

<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>

2、添加swagger UI 配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                //apiInfo指定测试文档基本信息,这部分将在页面展示
                .apiInfo(apiInfo())
                .select()
                //apis() 控制哪些接口暴露给swagger,
                // RequestHandlerSelectors.any() 所有都暴露 可省略
                // RequestHandlerSelectors.basePackage("com.info.*")  指定包位置 可省略
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    //基本信息,页面展示
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("测试项目标题")
                .description("接口描述")
                //版本号
                .version("1.0")
                .build();
    }
}

3、Controller类上加注解

@RestController
@RequestMapping
//Api注解,描述信息 可通过tags进行分类
@Api(value = "TestController", description = "TestController", tags = "测试")  // swagger UI注解
public class TestController {
    @PostMapping("/getUserByParam")
    @ApiOperation(notes = "查看人员", value = "getUserByParam") // swagger UI注解
    public User getUserByParam(
            @ApiParam(name = "name", value = "姓名") @RequestParam("name") String name,
            @ApiParam(name = "age", value = "年龄")  @RequestParam("age") Integer age) {
       // 省略
    }
}

4、访问&测试

根据 localhost:8080/swagger-ui.html 地址访问,进入页面可以对对应的接口进行测试,使用非常方便。

 类似资料: