swagger 整合springmvc

来源:互联网 发布:3d360度全景图制作知乎 编辑:程序博客网 时间:2024/06/04 19:57

一:引入下面的依赖

<!-- swagger-springmvc -->    <dependency>        <groupId>com.mangofactory</groupId>        <artifactId>swagger-springmvc</artifactId>        <version>1.0.2</version>    </dependency>    <dependency>        <groupId>com.mangofactory</groupId>        <artifactId>swagger-models</artifactId>        <version>1.0.2</version>    </dependency>    <dependency>        <groupId>com.wordnik</groupId>        <artifactId>swagger-annotations</artifactId>        <version>1.3.11</version>    </dependency>    <!-- swagger-springmvc dependencies -->    <dependency>        <groupId>com.google.guava</groupId>        <artifactId>guava</artifactId>        <version>15.0</version>    </dependency>    <dependency>        <groupId>com.fasterxml.jackson.core</groupId>        <artifactId>jackson-annotations</artifactId>        <version>2.4.4</version>    </dependency>    <dependency>        <groupId>com.fasterxml.jackson.core</groupId>        <artifactId>jackson-databind</artifactId>        <version>2.4.4</version>    </dependency>    <dependency>        <groupId>com.fasterxml.jackson.core</groupId>        <artifactId>jackson-core</artifactId>        <version>2.4.4</version>    </dependency>    <dependency>        <groupId>com.fasterxml</groupId>        <artifactId>classmate</artifactId>        <version>1.1.0</version>    </dependency>

  以上是比较完整的依赖列表,本文搭建的项目可以正常运行。读者可能会有疑问,maven管理的依赖包不是具有传递性吗?是的,是有传递性,但是传递性是根据来界定的。打开swagger-springmvc依赖包的pom文件可以发现,其很多依赖包的scope值为compile或者provider,不会根据传递性自动引入。

二:swagger配置
新建一个类代码如下:

package com.chltec.vendor.config;import com.mangofactory.swagger.configuration.SpringSwaggerConfig;import com.mangofactory.swagger.models.dto.ApiInfo;import com.mangofactory.swagger.plugin.EnableSwagger;import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.EnableWebMvc;@Configuration@EnableSwagger@EnableWebMvc@ComponentScan(basePackages = {        "com.chltec.vendor.controller" })public class SwaggerConfig {    private SpringSwaggerConfig springSwaggerConfig;    /**     * Required to autowire SpringSwaggerConfig     */    @Autowired    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig)    {        this.springSwaggerConfig = springSwaggerConfig;    }    /**     * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc     * framework - allowing for multiple swagger groups i.e. same code base     * multiple swagger resource listings.     */    @Bean    public SwaggerSpringMvcPlugin customImplementation()    {        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)                .apiInfo(apiInfo())                .includePatterns(".*?");    }    private ApiInfo apiInfo()    {        ApiInfo apiInfo = new ApiInfo(                "My Apps API Title",                "My Apps API Description",                "My Apps API terms of service",                "My Apps API Contact Email",                "My Apps API Licence Type",                "My Apps API License URL");        return apiInfo;        //访问地址;http://localhost:8080/swagger/index.html   swagger-ui2.0版本可以出现界面。swagger-ui3.0版本会出现No operations defined in spec    }}

SpringSwaggerConfig无法注入。因为spring容器里没有SpringSwaggerConfig类型的对象。解决办法:在springmvc的配置文件中加入以下配置即可。


  到目前为止,我们已经完成了对所有接口方法的扫描解析功能,那解析得到什么内容呢?这需要我们自定义,自定义操作的对象就是接口方法。先看段代码:
  /**
* 根据用户名获取用户对象
* @param name
* @return
*/
@RequestMapping(value=”/name/{name}”, method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = “根据用户名获取用户对象”, httpMethod = “GET”, response = ApiResult.class, notes = “根据用户名获取用户对象”)
public ApiResult getUserByName(@ApiParam(required = true, name = “name”, value = “用户名”) @PathVariable String name) throws Exception{
UcUser ucUser = ucUserManager.getUserByName(name);

if(ucUser != null) {    ApiResult<UcUser> result = new ApiResult<UcUser>();    result.setCode(ResultCode.SUCCESS.getCode());    result.setData(ucUser);    return result;} else {    throw new BusinessException("根据{name=" + name + "}获取不到UcUser对象");}

}

 @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)    @ResponseBody    public ResponseEntity<BaseResponse> updatePassword(@RequestParam("old_password") String old_password,@RequestParam("new_password") String new_password,@RequestParam("confirm_password") String confirm_password,@RequestParam("phone_number") String phone_number){        Agent agent =agentService.findByPhoneNumber(phone_number);        if(agent==null){            return new ResponseEntity<BaseResponse>(new BaseResponse(ResponseCode.NO_REGISTER), HttpStatus.OK);        }else {        ......    }

  上述代码是Controller中的一个方法,@ApiOperation注解对这个方法进行了说明,@ApiParam注解对方法参数进行了说明。关于这两个注解的使用,可以参看源码。这样子,Swagger就可以扫描接口方法,得到我们自定义的接口说明内容。

 说明:  其中@ApiOperation和@ApiParam为添加的API相关注解,个参数说明如下:  @ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明”;其他参数可参考源码;  @ApiParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”

三、Swagger-UI配置

  Swagger扫描解析得到的是一个json文档,对于用户不太友好。下面介绍swagger-ui,它能够友好的展示解析得到的接口说明内容。

  从https://github.com/swagger-api/swagger-ui 获取3.0版本以下,2.0版本以上。其所有的 dist 目录下东西放到需要集成的项目里,本文放入 src/main/webapp/WEB-INF/swagger/ 目录下。

  修改swagger/index.html文件,默认是从连接http://petstore.swagger.io/v2/swagger.json获取 API 的 JSON。http://localhost:8080/swagger/index.html

  因为swagger-ui项目都是静态资源,restful形式的拦截方法会将静态资源进行拦截处理,所以在springmvc配置文件中需要配置对静态文件的处理方式。

//所有swagger目录的访问,直接访问location指定的目录

  以下为接口文档形式图:
这里写图片描述

注:swagger最好用2.0版本,3.0会出现No operations defined in spec问题。

参考文章:http://www.cnblogs.com/jtlgb/p/6734177.html