swagger2.0与spring结合

官方文档:
 
swagger是一个前后端api统一文档和测试框架,注意,不光是一个api文档,还可以测试
 
  • 怎么使用呢 这里慢慢道来,我们一般用的都是maven工程,所以这里直接上maven依赖
<swagger.version>1.5.8</swagger.version>
<io.springfox.version>2.5.0</io.springfox.version>
<!-- swagger start -->
<dependency>
  <groupId>io.swagger</groupId>
  <artifactId>swagger-core</artifactId>
  <version>${swagger.version}</version>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>${io.springfox.version}</version>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>${io.springfox.version}</version>
</dependency>
<!-- swagger end -->

 

 
  • 这里我们需要注入SwaggerConfiguration配置,直接上代码
/**
 * Created by max on 8/16/16.
 *
 */
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket getApiInfo() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("outer api")
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .apiInfo(outApiInfo());

    }

    private ApiInfo outApiInfo() {
        return new ApiInfo(
                "mylearn 前后端接口-外部", // title 标题
                "外部接口文档", // description 描述 标题下
                "1.0.0", // version
                "http://mylearn/*", // termsOfService
                new Contact("xieyuebin","","xieyuebin@meituan.com"), // contact
                "Apache 2.0", // licence
                "http://www.apache.org/licenses/LICENSE-2.0.html" // licence url
        );

    }

    @Bean
    public UiConfiguration getUiConfig() {
        return new UiConfiguration(
                null,// url,暂不用
                "none",       // docExpansion          => none | list
                "alpha",      // apiSorter             => alpha
                "schema",     // defaultModelRendering => schema
                UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS,
                false,        // enableJsonEditor      => true | false
                true);        // showRequestHeaders    => true | false
    }
这是对于文档的说明以及ui的一些配置
 
  • 然后我们还需要把swagger和spring mvc结合起来,首先在web.xml里加入swagger文档的访问路径:
<!-- swagger ui 的静态资源交由default处理-->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/swagger-ui.html</url-pattern>
    </servlet-mapping>

 

 
  • 然后我们在dispatch-servlet.xml里加入对swagger静态资源jar包的访问路径如下:
<!-- swagger 配置 ,线上版本需要注释掉 -->
    <beans:bean class="com.meituan.maxtse.mylearn.swagger.SwaggerConfiguration"/>
    <!-- swagger ui resources-->
    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars"/>

 

这里我们用到了我们前面定义的SwaggerConfiguration类
  • 然后我们在controller和请求参数和返回参数里加入swagger提供的注解,直接上例子
入参:
/**
 * Created by max on 10/11/16.
 */
@ApiModel(description = "用户请求表单")
public class UserForm {

    @ApiModelProperty(value = "姓名", example = "maxTse",position = 1)
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "UserForm{" +
                "username='" + username + '\'' +
                '}';
    }
}

 

返回值:
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel
public class OutResult<T> implements Serializable {

    @ApiModelProperty(value = "数据", example = "")
    public T data;

    @ApiModelProperty(value = "状态码,0表示成功 其他表示失败", example = "0")
    public int status;

    @ApiModelProperty(value = "错误信息", example = "操作成功")
    public String message = "";

 

controller:
/**
 * Created by max on 8/16/16.
 */
@Controller
@RequestMapping(value = "/test", consumes = "application/json", produces = "application/json")
public class TestController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);

    @ApiOperation(value = "swagger test", notes = "swagger test first", tags = {SwaggerConstants.TEST_TAG})
    @ResponseBody
    @RequestMapping(value = "/first", method = RequestMethod.POST)
    public OutResult<String> first(@RequestBody UserForm userForm) {
        LOGGER.info("first userForm={}", userForm);
        throw new RuntimeException("dd");
/*
        return OutResult.successResult(userForm.getUsername());
*/
    }

 

这里挨个注解解释下:
@ApiModel 表明这是一个被swagger框架管理的model,用于class上
@ApiModelProperty 这里顾名思义,就是标注在被标注了@ApiModel的class的属性上,
这里的value是对字段的描述,example是取值例子,注意这里的example很有用,对于前后端开发工程师理解文档起到了关键的作用,因为会在api文档页面上显示出这些取值来;这个注解还有一些字段取值,可以自己研究,举例说一个:position,表明字段在model中的顺序
@ApiOperation标注在具体请求上,value和notes的作用差不多,都是对请求进行说明;tags则是对请求进行分类的,比如你有好几个controller,分别属于不同的功能模块,那这里我们就可以使用tags来区分了,看上去很有条理
  • 下面我们启动项目,然后通过url:localhost:8080/swagger-ui.html来访问,就可以看到swagger文档界面了 

 

这里是请求和返回结果的界面,看到这个界面是不是对刚才我们贴出来的具体例子里的注解上的每个值有所了解了,一一对应便能了解他们的作用
我们开始说了,这个不仅可以当文档使,而且还可以进行测试,没错,看看参数界面大家都知道了,实际上参数界面就在请求和返回结果的下面:
 
看到右上方的大红框,就是我们的入参格式,注意,这里是json格式的
然后我们可以在具体填入自己的请求参数后,点击下方的try it out按钮,就可以进行测试了。
总结:
使用swagger2.0框架大概这么几步:
1.添加maven依赖
2.编写SwaggerConfiguration配置
3.web.xml里添加swagger文档的访问路径,是静态资源
4.添加相关的spring mvc配置
5.在请求的入参和返回值 以及具体的请求上添加相应的注解
6.启动项目,访问swagger.html
注意
由于这里使用的是json格式的入参和返回值,那么我们在controller的请求参数那里要加上@RequestBody注解,并且请求方法必须是post
 
 
 
posted @ 2016-10-11 18:23  我爱马培培  阅读(17861)  评论(0编辑  收藏  举报