Spring MVC 中使用 Swagger2 构建动态 RESTful API

   当多终端(WEB/移动端)需要公用业务逻辑时,一般会构建 RESTful 风格的服务提供给多终端使用。

   为了减少与对应终端开发团队频繁沟通成本,刚开始我们会创建一份 RESTful API 文档来记录所有接口细节。

   但随着项目推进,这样做所暴露出来的问题也越来越严重。

   a. 接口众多,细节复杂(需考虑不同的 HTTP 请求类型、HTTP 头部信息、HTTP 请求内容..),高质量地创建这份文档本身就是件非常吃力的事。

   b. 不断修改接口实现必须同步修改接口文档,而文档与代码又处于两个不同的媒介,除非有严格的管理机制,不然很容易导致不一致现象。

   基于此,项目组在早些时间引入了 Swagger,经过几个项目的沉淀,确实起到了很不错的效果。

   Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

   服务的方法、参数、模型紧密集成到服务器端的代码,让维护文档和调整代码融为一体,使 API 始终保持同步。

   本文主要描述 Swagger 与 SpringMVC 的集成过程以及遇到的一些问题,权当抛砖引玉只用,具体项目具体分析。

  

1. Maven 依赖和最简配置

      <!--restfull APi swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>

   Spring-Context  Swagger 配置:

    <!-- swagger2 配置类-->
    <bean id="config" class="com.rambo.spm.core.config.SwaggerConfig"/>

    <!-- swagger2 静态资源交由 spring 管理映射(springfox-swagger-ui.jar 为静态资源包)-->
    <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

   <mvc:resources /> 由 Spring MVC 处理静态资源,并添加一些有用的附加值功能。

   a. <mvc:resources /> 允许静态资源放在任何地方,如 WEB-INF 目录下、类路径下等,完全打破了静态资源只能放在 Web 容器的根路径下这个限制。

   b.<mvc:resources /> 依据当前著名的 Page Speed、YSlow 等浏览器优化原则对静态资源提供优化。

   SwaggerConfig 配置类:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder();
        apiInfoBuilder.title("SPM Doc");
        apiInfoBuilder.description("SPM Api文档");
        apiInfoBuilder.contact(new Contact("orson", "https://www.cnblogs.com/", ""));
        apiInfoBuilder.version("2.0");
        return apiInfoBuilder.build();
    }
}

   对于生成哪些请求方法 API ? Swagger 提供了 RequestHandlerSelectors 对象的以下方法进行限制范围:

2. 服务注解配置实践

   经过上述的操作,其实 Swagger 已经集成完毕,在项目开发推进中,只需在对应 RESTful 服务上添加对应注解即可。

  @Api:注解在类上,说明该类的作用。可以标记一个 Controller 类做为 swagger  文档资源,使用方式:

@Api(description = "用户管理")

   @ApiOperation:注解在方法上,说明方法的作用,每一个url资源的定义,使用方式:

@ApiOperation(value = "获取所有用户列表")

   @ApiParam、@ApiImplicitParam:注解到参数上,说明该参数作用,使用方式:

@ApiParam(value = "用户ID") String userId

   上述都为最简配置,构建清晰的 API  文档已足够,当然还有很丰富的注解,知道有就行了。

@RestController
@Api(description = "用户管理")
public class UserRestController extends BaseController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("r/user/get")
    @ApiOperation(value = "获取特定用户详情")
    public Object getUser(ModelMap modelMap, @ApiParam(value = "用户ID") String userId) {

    }

    @PostMapping("r/user/add")
    @ApiOperation(value = "添加用户")
    public Object addUser(ModelMap modelMap, @ModelAttribute @Valid SysUser user, BindingResult result) {

    }
}

   在项目后续使用中遇到的一些问题:

a. 一些方法入参如 HttpServletRequest、HttpServletResponse、HttpSession、ModelMap 等等,这些参数在生成 API 文档时是无意义的,Swagger 正确的配置方式?

   刚开始时使用 @ApiParam(hidden = true)  注解这些参数,方法繁多的时候,这些类型的入参都要写一遍,使用起来很冗余。

   在 API 中发现 Docket 对象有 ignoredParameterTypes 方法,在配置类中统一定义忽略的参数类型即可,这样就方便很多。

public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .ignoredParameterTypes(ModelMap.class, HttpServletRequest.class,HttpServletResponse.class, BindingResult.class)
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

b. 当请求的参数为封装的对象时,怎样进行注解?对象中的属性怎样注解?怎样屏蔽对象中的莫个属性?

   请求的参数为对象时,使用Spring @ModelAttribute 注解对应对象,对象当中的属性使用 @ApiModelProperty ,屏蔽莫个属性 @ApiModelProperty(hidden = true)

    @ApiModelProperty(hidden = true)
    private String uuid;

    @ApiModelProperty("姓名")
    private String name;

    @ApiModelProperty("密码")
    private String passwd;

c. @Api 注解中的 tags 值不支持中文,中文值会导致无法展开;

   Swagger 有很丰富的工具,还能做很多事,本文所述只是能让你迅速了解它、使用它、有需要多查资料、多翻博客。

 

posted @ 2017-09-19 14:48  Orson  阅读(1973)  评论(1编辑  收藏  举报