Java restfull API documentation Generation Swagger Ui__java

Source: Internet
Author: User
Tags documentation
Original address: http://javatech.wang/index.PHP/archives/74/
The author is currently building a set of API service framework, considering that the client can be more convenient to invoke the API service (more convenient is to avoid the trouble to explain the parameters required by the interface and return results), so determined to generate detailed documentation for each interface. Online search for a moment, found swagger this thing, feel good, interface is also more than Javadoc generated pages to be beautiful, and online on swagger and SPRINGMVC integration of many articles (unfortunately most of the same and incomplete). This article introduces the integration process of swagger and SPRINGMVC in detail, focusing on making up for the omission of existing articles (very important. )。 Let's learn how to use swagger to generate interface documents.

Since it is the integration of swagger, then the premise is that you have used SPRINGMVC to build a set of interface services , regardless of simplified, as long as available on the line. About the interface document Generation tool, when you search the Internet, you may find another tool: Springfox. There are also a lot of articles online about Springfox and spring integration. What is the relationship between Springfox and swagger? Quote Springfox's Official quotations:

Springfox has evolved from a project originally created by Marty Pitt and is named Swagger-springmvc. 

This paragraph of English is very simple, do not understand the reader control online dictionary can also be translated, refueling. To get to the bottom of this, let's briefly introduce the project environment: JDK1.7 Spring 3.2.2 Swagger-springmvc 1.0.2 (latest version) One, dependency management

Before you integrate, you need to introduce all of the dependent packages you use. many articles on the web simply tell the reader to introduce the Swagger-springmvc-1.0.2.jar package, but then you find that this is far from enough and requires a lot of packages, as shown below:

<!--swagger-springmvc--> <dependency> <groupId>com.mangofactory</groupId> &L
    T;artifactid>swagger-springmvc</artifactid> <version>1.0.2</version> </dependency> <dependency> <groupId>com.mangofactory</groupId> <artifactid>swagger-models&lt ;/artifactid> <version>1.0.2</version> </dependency> <dependency> <g Roupid>com.wordnik</groupid> <artifactId>swagger-annotations</artifactId> <version >1.3.11</version> </dependency> <!--swagger-springmvc dependencies--> <dependency&gt
        ; <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> </depen dency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactid& gt;jackson-databind</artifactid> <version>2.4.4</version> </dependency> <depend Ency> <groupId>com.fasterxml.jackson.core</groupId> <artifactid>jackson-core</arti factid> <version>2.4.4</version> </dependency> <dependency> <groupid >com.fasterxml</groupId> <artifactId>classmate</artifactId> <version>1.1.0</
 Version> </dependency>

The above is a more complete list of dependencies, the project can be built in the normal operation. Readers may have doubts that the dependencies managed by Maven are not transitive. Yes, there is transitivity, but transitivity is defined by <scope>. Opening the SWAGGER-SPRINGMVC-dependent pom file reveals that many of its dependencies are either compile or provider, and are not automatically introduced according to Transitivity. Second, swagger configuration

The swagger configuration is actually a custom config class that implements configuration in Java encoding. The code is as follows:

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.Configuration;
 /** * Created by Xiaohui on 2016/1/14.

    * * @Configuration @EnableSwagger public class Swaggerconfig {private Springswaggerconfig springswaggerconfig; /** * Required to Autowire springswaggerconfig/@Autowired public void Setspringswaggerconfig (SPRINGSW
    Aggerconfig springswaggerconfig) {this.springswaggerconfig = Springswaggerconfig; }/** * Every Swaggerspringmvcplugin Bean is picked up to SWAGGER-MVC * framework-allowing for Multip
 Le 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 contacts E
        Mail "," My Apps API Licence Type "," My Apps API License URL ");
    return apiinfo;
 }
}

The above code is found on the Web, you must have found it, right. However, you will find a problem: Springswaggerconfig cannot be injected. this is why. It's very simple, because there is no Springswaggerconfig type object in the Spring container. Workaround: Add the following configuration to the SPRINGMVC configuration file.

<bean class= "Com.mangofactory.swagger.configuration.SpringSwaggerConfig"/>

So far, we've done the scanning parsing of all the interface methods, so what does the parsing get? This requires customization, and the object of the custom action is the interface method. Read the snippet First:

/**
 * Get User Object
 * @param name
 * @return
/@RequestMapping (value= "/name/{name}") based on user name, method = Requestmethod.get)
@ResponseBody
@ApiOperation (value = "Get user object according to user name", HttpMethod = "getting", response = Apiresult.class, notes = "Get user object based on user name") Public
Apiresult Getuserbyname (@ApiParam (required = true, name = "Name", Valu E = "User name" @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 ("Ucuser object not obtained from {name=" + Name +}}}

The above code is a method in controller, which is described @ApiOperation annotation, @ApiParam annotation is used to illustrate the method parameters. For the use of these two annotations, you can refer to the source code. In this way, swagger can scan the interface method to get our custom interface description. Third, swagger-ui configuration

Swagger scan parsing gets a JSON document that is not very friendly to the user. The following is an introduction to Swagger-ui, which provides a friendly display of the parsed interface description.

From the Https://github.com/swagger-api/swagger-ui get all of their dist directories into items that need to be integrated, this article is placed in the src/main/webapp/web-inf/swagger/directory.

Modifying the swagger/index.html file, by default, gets the JSON for the API from the connection Http://petstore.swagger.io/v2/swagger.json, where the URL value needs to be modified to http://{ip}:{ In the form of Port}/{projectname}/api-docs, the value in {} is filled in according to its own situation. For example, my URL value is: Http://localhost:8083/arrow-api/api-docs

Because Swagger-ui projects are static resources, restful blocking methods will intercept static resources, so you need to configure how static files are handled in SPRINGMVC configuration files.

Access to all swagger directories, directly accessing the directory specified by location <mvc:resources mapping= "/swagger/**" location= "/web-inf/swagger/"/>

Ok. The success, open the browser directly to access the swagger directory of index.html files, you can see the interface document description. Pay attention to access to the address Oh. Look at the picture below:




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.