SpringBoot

SpringBoot2.0配置Swagger2

2018-11-04  本文已影响0人  雨落千木的时节

在工作中,不管是前后端分离,还是微服务,还是其他方式的接口的调用,都需要编写和维护接口文档。Swagger可以帮助我们更好的编写和维护API文档,提供Restful风格的API,提供的maven依赖可以更好的集成在spring项目中。
springboot使用swagger超级简单:
1.添加maven依赖:

        <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.添加swagger配置

package com.yixin.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created by shaomaolin on 2018/11/2.
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //swagger要扫描的包路径
                .apis(RequestHandlerSelectors.basePackage("com.yixin.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot Swagger 测试")
                .description("Springboot 整合Swagger2")
                .termsOfServiceUrl("localhost:8080/ruleengine")
                .contact(new Contact("Swagger测试","localhost:8080/ruleengine/swagger-ui.html","baidu@qq.com"))
                .version("1.0")
                .build();
    }

}

3.swagger扫描的包中添加文档说明

package com.yixin.controller;

import com.google.common.base.Preconditions;
import com.yixin.model.RuleUser;
import com.yixin.model.response.RuleUserResponse;
import com.yixin.service.RuleUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * Created by shaomaolin on 2018/11/2.
 */
@Api(value = "用户接口")
@Log4j2
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RuleUserService userService;

    @ApiOperation(value = "获取用户", notes = "根据id查询用户信息")
    @ApiImplicitParam(name = "id", value = "用户id", required=true, dataType = "String")
    @ResponseBody
    @GetMapping(value = "/queryUser")
    public RuleUserResponse queryRuleUser(String id) {
        RuleUserResponse resp = new RuleUserResponse();
        try {
            RuleUser user = userService.queryOne(id);
            Preconditions.checkNotNull(user, "查询用户信息为空!");

            BeanUtils.copyProperties(resp, user);
            return resp;
        } catch (Exception e) {
            log.error("查询用户失败!", e);
            throw new RuntimeException(e.getMessage());
        }

    }
}

启动springboot项目,浏览器输入http://localhost:8080/ruleengine/swagger-ui.html,就可以看到接口文档了。

image.png

注意:输入地址是一定要将springboot中配置的server.servlet.path路径加上,否则会报404错误。
Swagger注解说明:
官网wiki地址:https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X#quick-annotation-overview

@Api:表示标识这个类是swagger的资源 
@ApiOperation:描述针对特定路径的操作或HTTP方法
@ApiImplicitParam:表示API操作中的单个参数
@ApiImplicitParams:允许多个ApiImplicitParam对象列表的包装器
@ApiModel:提供关于Swagger模型的额外信息
@ApiModelProperty:添加和操作模型属性的数据
@ApiParam:为操作参数添加额外的元数据
@ApiResponse:描述一个操作的可能响应
@ApiResponses:允许多个ApiResponse对象列表的包装器
@ResponseHeader:表示可以作为响应的一部分提供的标头
@Authorization:声明要在资源或操作上使用的授权方案
@AuthorizationScope:描述OAuth2授权范围

接口文档管理不一定要使用swagger,也有用阿里的RAP管理文档。
Swagger 和 RAP 的对比:
Swagger优势:
1.编写代码的过程中通过注解的方式编写接口文档
2.项目启动后直接可以访问,不需要单独部署
3.Restful风格的API
4.Swagger是一个开源框架,支持codegen,editor,ui等许多强大的功能,本文只是做了个简单的介绍,此外我们可以定制化开发
缺点:
不支持Mock调用,需要其他mock插件支持
RAP有点:
1.支持Mock调用
2.支持团队功能,方便团队管理
3.支持json或者xml直接导入
缺点:
1.需要单独部署在tomcat容器中
2.不能自动生成,需要手动录入接口文档,接口变化比较时需要单独去维护。

上一篇 下一篇

猜你喜欢

热点阅读