美文网首页
Spring Boot整合swagger2

Spring Boot整合swagger2

作者: wencai | 来源:发表于2018-01-03 15:52 被阅读0次

参考:

http://blog.csdn.net/amon1991/article/details/76774880
http://blog.didispace.com/springbootrestfulapi/


一、为什么要用swagger2

1.手动录入API的缺点:

1)由于需求或设计的原因,并不能保证一次就可将接口确定,不再做变动,频繁的修改接口可能会导致接口文档和实际接口不一致;

2)不能直接在线测试接口,需使用其他工具,如postman

2.解决方案

swagger完美解决了以上两个问题,既能在线测试接口,又能动态生成api文档,只需在接口上加适当的备注。

3.swagger缺点

1)代码侵入性强

2)必须启动接口服务器,才能访问到接口文档


二、swagger2使用

1.添加pom依赖

添加swagger2核心包和swagger-ui界面包。

                <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>
2.配置api文档页基本信息

与启动类同级,特别注意里面配置了API文件也就是controller的路径,不然生成的文档扫描不到接口。


@Configuration

@EnableSwagger2

public class Swagger2{ 

 @Bean 

 public Docket createRestApi() {

        return new Docket(DocumentationType.SWAGGER_2)

                .apiInfo(apiInfo())

                .select()

                .apis(RequestHandlerSelectors.basePackage("com.xx.web.controller"))

                .paths(PathSelectors.any())

                .build();

    }

    private ApiInfo apiInfo() {

        return new ApiInfoBuilder()

                .title("xx项目 RESTful APIs")

                .description("xx项目后台api接口文档")

                .version("1.0")

                .build();

    }

}

spring-boot和swagger整合时,可以通过注解注入相关配置。通过这些配置可指定在spring-boot启动时扫描哪些controller层的文件夹,另外可指定api文档页的标题和描述信息等内容。

3.API文档编写示例

一般在controller层,将详尽的API接口输入输出在代码中通过注解进行相关描述。


@Api(value = "PageController", description = "用户登录登出接口")

@Controller

@RequestMapping("/")

public classPageController{ 

    @ApiOperation(value="用户登录", notes="用户登录接口")

    @ApiImplicitParams({

          @ApiImplicitParam(name = "username", value = "用户名", required = true ,dataType = "string"),

          @ApiImplicitParam(name = "passwd", value = "密码", required = true ,dataType = "string")

    })

    @RequestMapping(value = "/login",method = {RequestMethod.POST,RequestMethod.GET})

    @ResponseBody    

     public ModelMap login(Users data, HttpServletRequest request){

      xxx...

    }

}

4.在线查看及测试API文档

http://127.0.0.1:8080/swagger-ui.html

相关文章

网友评论

      本文标题:Spring Boot整合swagger2

      本文链接:https://www.haomeiwen.com/subject/hhzigxtx.html