Swagger與SpringMVC項目整合,swaggerspringmvc

來源:互聯網
上載者:User

Swagger與SpringMVC項目整合,swaggerspringmvc
Swagger與SpringMVC項目整合

為了方便的管理項目中API介面,在網上找了好多關於API介面管理的資料,感覺目前最流行的莫過於Swagger了,功能強大,UI介面漂亮,並且支援線上測試等等,所以本人仔細研究了下Swagger的使用,下面就如何將Swagger與個人的SpringMVC項目進行整合做詳細說明:

最終API管理介面:

詳細步驟:

Step1:項目中引入相關jar包:
    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <version.spring>3.2.9.RELEASE</version.spring>        <version.jackson>2.4.4</version.jackson>    </properties>    <dependencies>        ....        <dependency>            <groupId>com.mangofactory</groupId>            <artifactId>swagger-springmvc</artifactId>            <version>0.9.5</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-annotations</artifactId>            <version>${version.jackson}</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-databind</artifactId>            <version>${version.jackson}</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-core</artifactId>            <version>${version.jackson}</version>        </dependency>    </dependencies>
Step2:添加自訂config檔案
package com.spg.apidoc.common.configer;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;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;/** * 項目名稱:apidoc * * @description: * @author Wind-spg * @create_time:2015年2月10日 上午10:27:51 * @version V1.0.0 * */@Configuration@EnableSwagger// Loads the spring beans required by the frameworkpublic class MySwaggerConfig{    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;    }}
Step3:將此配置加入到Spring容器中,如下:
<bean class="com.spg.apidoc.common.configer.MySwaggerConfig" />
Step4:在代碼中添加相關APIAnnotation,如下:
    @ResponseBody    @RequestMapping(            value = "addUser", method = RequestMethod.POST, produces = "application/json; charset=utf-8")    @ApiOperation(value = "添加使用者", httpMethod = "POST", response = BaseResultVo.class, notes = "add user")    public String addUser(@ApiParam(required = true, name = "postData", value = "使用者資訊json資料") @RequestParam(            value = "postData") String postData, HttpServletRequest request)    {        LOGGER.debug(String.format("at function, %s", postData));        if (null == postData || postData.isEmpty())        {            return super.buildFailedResultInfo(-1, "post data is empty!");        }        UserInfo user = JSON.parseObject(postData, UserInfo.class);        int result = userService.addUser(user);        return buildSuccessResultInfo(result);    }

說明:
其中@ApiOperation和@ApiParam為添加的API相關註解,個參數說明如下:
@ApiOperation(value = “介面說明”, httpMethod = “介面請求方式”, response = “介面返回參數類型”, notes = “介面發布說明”;其他參數可參考源碼;
@ApiParam(required = “是否必須參數”, name = “參數名稱”, value = “參數具體描述”

Step5:添加Swagger UI配置

在GitHub上下載SwaggerUI項目,將dist下所有內容拷貝到本地項目webapp下面,結果目錄如所示:

Step6:修改index.html

將index.html中http://petstore.swagger.wordnik.com/v2/swagger.json修改為http://localhost:8080/{projectname}/api-docs

到此為止,所有配置完成,啟動你的項目,訪問http://localhost:8080/{projectName}/index.html即可看到如下所示頁面:

項目最終demo可見個人GitHub
https://github.com/itboyspg/spg-code/tree/master/apidoc
參考:
https://github.com/martypitt/swagger-springmvc
https://github.com/swagger-api/swagger-ui

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.