SPRINGMVC integrated swagger for automatic generation of interface documentation

Source: Internet
Author: User

have been suffering from the document collation work, because this is a very boring job, accidentally saw on the net swagger this thing, feel good, so hands-on integration of a bit, in front of a bright

Swagger is a normative and complete framework for generating, describing, invoking, and visualizing RESTful Web services. The overall goal is to have the client and the file system update at the same speed as the server. File methods, parameters and models are tightly integrated into the server-side code, allowing the API to always stay in sync. Swagger making deployment management and using powerful APIs has never been easier.

Crap less, take a look at the integration process, I use the environment is: jdk1.8+tomcat7.0+springmvc4.2+maven3.0

1. First, bring the relevant jar into the project through MAVEN

    <!--swagger--<dependency> <groupid>com.mangofactory</groupid&gt                  ;              <artifactId>swagger-springmvc</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupid>com.fasterxml.jackson.dataformat</g Roupid> <artifactId>jackson-dataformat-xml</artifactId> <version>2. 7.4</version> </dependency> <dependency> &LT;GROUPID&GT;COM.F                  Asterxml.jackson.core</groupid> <artifactId>jackson-databind</artifactId>                  <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactid>jackson-annotations</arti Factid> <version>2.7.4</version> </dependency> &LT;DEPENDENCY&G                  T <groupId>com.fasterxml.jackson.core</groupId> &LT;ARTIFACTID&GT;JACKSON-CORE&LT;/ARTIFACTID&G                  T   <version>2.7.4</version> </dependency> <!--swagger--

2. Write a custom Swagger config class

    Importorg.springframework.beans.factory.annotation.Autowired; ImportOrg.springframework.context.annotation.Bean; ImportOrg.springframework.context.annotation.ComponentScan; Importorg.springframework.context.annotation.Configuration; ImportORG.SPRINGFRAMEWORK.WEB.SERVLET.CONFIG.ANNOTATION.ENABLEWEBMVC; ImportCom.mangofactory.swagger.configuration.SpringSwaggerConfig; ImportCom.mangofactory.swagger.models.dto.ApiInfo; ImportCom.mangofactory.swagger.plugin.EnableSwagger; ImportCom.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin; /*** <B> file name:</b>swaggerconfig.java<br> * <B> File Description:</b><br> * * <B> Copyright:</b> (C) 2014-2015<br> * <B> Company Department:</b><br> * <B> creation time: </b>20 June 30, 16 <BR> * *@author       * @version       */@Configuration @EnableWebMvc @EnableSwagger @ComponentScan ("Cn.brandwisdom.roomVouchers")       Public classSwaggerconfig {PrivateSpringswaggerconfig Springswaggerconfig; @Autowired Public voidsetspringswaggerconfig (Springswaggerconfig springswaggerconfig) { This. Springswaggerconfig =Springswaggerconfig; }                /*** Chained programming to customize the API style * followed by grouping information * *@return          */@Bean PublicSwaggerspringmvcplugin customimplementation () {return NewSwaggerspringmvcplugin ( This. springswaggerconfig). Apiinfo (Apiinfo ()). IncludePatterns (".*"). Apiversion ("0.0.1"); //. Swaggergroup (PROJECT_NAME);         }                Privateapiinfo Apiinfo () {apiinfo apiinfo=NewApiinfo ("My Apps API Title", "My Apps apidescription", "My Apps API terms Ofservice",                      "My Apps API Contactemail", "My Apps API Licencetype", "My Apps API Licenseurl"); returnApiinfo; }      }  

3. Give this class to spring for management

Class

4. By means of annotations, let Swagger be able to know the function description of our interface

@Controller @RequestMapping (value= "/user") @Api (value= "User")       Public classUsercontroller {/*** Get user objects based on user name *@paramname *@return       */@RequestMapping (Value= "/name/{name}", method =requestmethod.get) @ResponseBody @ApiOperation (value= "Get user object according to user name", HttpMethod = "get", response = Apiresult.class, notes = "Get user objects based on user name")       PublicApiresult Getuserbyname (@ApiParam (required =true, name = "Name", value = "User name") @PathVariable String name)throwsexception{ucuser Ucuser=ucusermanager.getuserbyname (name); if(Ucuser! =NULL) {Apiresult<UcUser> result =NewApiresult<ucuser>();              Result.setcode (ResultCode.SUCCESS.getCode ());              Result.setdata (Ucuser); returnresult; } Else {              Throw NewBusinessexception ("Cannot get Ucuser object based on {name=" + name + "}"); }      }            }  

Note: @API (value= "user") this is used to group, (but seemingly do not write can also be automatically grouped according to the controller), @ApiOperation annotations to this method is described, @ApiParam annotations to the method parameters are described.

4.swagger-ui Configuration

Swagger Scan Parsing is a JSON document that is not very user friendly. The following is an introduction to Swagger-ui, which is a friendly display of the interface descriptions that are parsed.

?? From Https://github.com/swagger-api/swagger-ui to get all of its dist directories into projects that need to be integrated, this article is placed in the src/main/webapp/api/directory (also can be placed in other directories).


?? To modify the index.html file, the default is to get the JSON of the API from the connection Http://petstore.swagger.io/v2/swagger.json, where you need to modify the URL value to http://{ip}:{port}/{ The Projectname}/api-docs form, the value in {} is filled in according to its own circumstances. For example, my URL value is: Http://localhost:8080/vouchers/api-docs

It is better to create a new src/main/webapp/api-docs/directory, for the program to generate the interface to the JSON file, I see the people on the Internet is not manually built, but I do not automatically generated, if you automatically generated, you can skip this step.

?? Because the Swagger-ui project is a static resource, the RESTful interception method will intercept the static resources, so you need to configure the processing of the static files in the SPRINGMVC configuration file (I've released all the files in the directory here).

ok! Done, open the api/, note that if you web. XML is not configured with the default welcome page, you want to add index.html access.


The following problems have been encountered in the project, referring to http://www.cnblogs.com/xmplatform/p/5785065.html

1, how to Chinese/show Chinese

The Swagger-ui itself is multi-lingual, with a piece of code in index.html:

<!--Some Basic translations-  <!--<script src= ' lang/translator.js ' type= ' Text/javascript ' >< /script>-  <!--<script src= ' lang/ru.js ' type= ' text/javascript ' ></script>  - <!--<script src= ' lang/en.js ' type= ' text/javascript ' ></script>-

Everyone just need to open the note, and add the corresponding Chinese JS can be, the final modification as follows:

<!--Some Basic translations-  <script src= ' lang/translator.js ' type= ' Text/javascript ' ></script >  <script src= ' lang/zh-cn.js ' type= ' text/javascript ' ></script>  <!--<script src= ' lang /en.js ' type= ' text/javascript ' ></script>-

2, in Swagger-ui the default parameters of the content type is Application/json, test found that the background parameters did not receive the value, how to do?

You might ask, what is the effect of Content type Application/json, and why should it be modified for others? Here will be involved in the SPRINGMVC will request to pass over the parameters injected into the controller method corresponding to the principle of the object, the specific knowledge you can search, this is not the focus of this article I will not talk about, in fact, we usually write the controller method, the default content The type is actually application/x-www-form-urlencoded, and the default content type of the parameter in swagger is Application/json, which causes the swagger test to be used. The corresponding parameter submitted to the Controller method could not be injected correctly.

    • So, how to deal with it, can you change it to another?

In fact, in the swagger-ui issues, someone mentioned, https://github.com/swagger-api/swagger-ui/issues/658, the solution is to set consumes this east.

    • The solution has been found, where is the consumes set?

The answer is to set the @apioperation in this annotation and change the consumes to "application/x-www-form-urlencoded", for example:

@ApiOperation (value= "Interface description (Test)", httpmethod= "GET", consumes= "application/x-www-form-urlencoded", notes= "in no session, Without a signature, enter the method body ")

    • So under what circumstances, the content type of the parameter is Application/json?

When you add a @requestbody annotation to the parameter, it means that this parameter receives JSON data, so you can write consumes as Application/json.

3, want to know apioperation annotation HttpMethod and other parameters can write which values?

This look at the API documentation, provide an address to everyone: http://docs.swagger.io/swagger-core/apidocs/com/wordnik/swagger/annotations/ApiOperation.html

SPRINGMVC integrated swagger for Interface document Automation generation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.