Springboot项目整合swagger2

IDEA下载swagger插件

File -> settings -> Plugins  搜索swagger并安装

pom文件添加依赖

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

Swagger配置类

@Configuration
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //扫描包的路径
                .apis(RequestHandlerSelectors.basePackage("com.jpa"))
                .paths(PathSelectors.any())
                .build();
    }
    //构建 api文档的详细信息函数
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("springboot利用swagger构建api文档")
                //创建人
                .contact("chegnjia")
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}

开启swagger

在启动类上添加@EnableSwagger2注解,开启swagger

@SpringBootApplication
@ComponentScan("com.jpa")//开启spring注解扫描
@EnableJpaRepositories(basePackages = {"com.jpa.repository"})//扫描JPA资源库
@EntityScan(basePackages = {"com.jpa.entity"})//扫描实体类
@EnableSwagger2//开启swagger
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

 

此时启动项目就可以访问http://localhost:8080/swagger-ui.html页面查看扫描路径下的接口文档了,只是因为项目中没有使用相关注解而没有任何注释。

 

swagger2 常用注解(非必要)

 

@Api放在类上面

@Api(description = "测试JPA接口")
public class BookController {

...

}

效果:

Springboot项目整合swagger2

 

@ApiOperation使用在接口上

@ApiOperation(value = "测试接口hello",notes = "用于测试项目能否运行")
@PostMapping("hello")
public String hello(){
    return "wellcome!";
}

效果:

Springboot项目整合swagger2

 

@ApiImplicitParam 与 @ApiImplicitParams

@ApiImplicitParam注解用于表明前端传入的name参数的名字,value是对参数的注释,example是样例参数,required是否为必需项,以及dataType参数类型,以及paramType传递方式(query表示使用url问号的方式传参,这种比较常用,如果使用formData的方式进行传参,那么paramType的值为 form)。

当有多个参数时,需要用@ApiImplicitParams将@ApiImplicitParam包起来

@ApiOperation(value = "测试使用jpa实现分页功能")
@ApiImplicitParams({
        @ApiImplicitParam(name = "page",value = "当前页码",example = "1",required = false,dataType = "int",paramType = "query"),
        @ApiImplicitParam(name = "size",value = "每页显示的数量",example = "5",required = false,dataType = "int",paramType = "query")
})
@PostMapping("noQuery")
public Page<BookEntity> findBookNoQuery(Integer page,Integer size){

....
}

 

效果:

Springboot项目整合swagger2

 

如果传递的是pojo类型的参数

 

Springboot项目整合swagger2

在ui.html中

Springboot项目整合swagger2

 

这里的Data Type为 Model,此时我们可以在实体类的代码中添加注解,选择我们需要在这里显示的属性。如下:

 

Springboot项目整合swagger2

@ApiModelProperty(hidden = true)表示不需要在swagger页面进行展示,required表示该属性为必需的属性。