Swagger使用简略

今天后端的朋友用了swagger管理接口,非常好用,记录一下。

第一步:添加依赖

这个可以在任意一个pom.xml里面布置,我这里放在Controller的pom.xml里面

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

第二步:把一个WebMvcConfigurer的实现类和启动项放在一起

image.png

在swagger2类中设置参数

@Configuration
@EnableSwagger2
public class Swagger2 implements WebMvcConfigurer {
    
    // 接口版本号
    private final String version = "1.0";
    // 接口大标题
    private final String title = "xxx接口";
    // 具体的描述
    private final String description = "公共数据服务接口文档";
    // basePackage
    private final String basePackage = "com.snnu.mbts.controller";
    
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .version(version)
                .build();
    }
}

第三步:在Controller类中设置接口信息

比如接口名称、接口信息,接口参数

@ApiOperation(value = "用户登陆请求", notes = "注意事项")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "用户名", required = true, paramType = "query", example = "张三"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query", example = "111111")
    })
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容