Using swagger to build development documents and front-end interactions

Source: Internet
Author: User
1.Swagger is what.

Official saying: Swagger is a normative and complete framework for generating, describing, invoking and visualizing RESTful-style Web services. The overall goal is to make the client and 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 remain synchronized.

Personally, one of the biggest advantages of swagger is the ability to synchronize APIs and documents in real time. In the course of project development, there have been many times: modify the code but did not update the document, the front-end or according to the old document development, in the process of the joint adjustment to find the problem (of course, according to the open and closed principle, the interface is not allowed to modify, but in the project instability phase, this situation is difficult to avoid 2.Spring Boot Integration Swagger2 I. Introduction of dependence:

Http://mvnrepository.com Search Springfox, introducing the Swagger2 and swagger UI dependencies:

<!--https://mvnrepository.com/artifact/io.springfox/springfox-swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>

        <!--https://mvnrepository.com/artifact/ Io.springfox/springfox-swagger-ui-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
second, start class demoapplication add @enableswagger2 annotation
@SpringBootApplication
@RestController
@EnableSwagger2 public
class DemoApplication {

    public static void Main (string[] args) {
        springapplication.run (demoapplication.class, args);
    }

    @GetMapping ("/hello") public
    String Hello () {return
        ' Hello Spring security ';
    }
}
Iii. Injecting the resource profile (configuration of the UI view)
@Configuration
@EnableSwagger2 Public
class Webconfig extends webmvcconfigureradapter{

    /**
     * This place needs to be injected into the resource file, or it will not inject resources, nor inject requesthandlermappping, equivalent to the XML configuration of
     *  <!--swagger resource configuration-->
     *  <mvc:resources location= "classpath:/meta-inf/resources/" mapping= "swagger-ui.html"/>
     *  <MVC: Resources location= "classpath:/meta-inf/resources/webjars/" mapping= "/webjars/**"/>
     *  don't know why, This is also a disadvantage of spring boot (rookie think)
     * @param Registry * * *
    @Override public
    void Addresourcehandlers ( Resourcehandlerregistry registry) {
        Registry.addresourcehandler ("swagger-ui.html")
                . Addresourcelocations ("classpath:/meta-inf/resources/");
        Registry.addresourcehandler ("/webjars*")
                . Addresourcelocations ("classpath:/meta-inf/resources/webjars/");
}
Four, start the service, access the localhost:8080/swagger-ui.html can see the service API documentation

@apimodelproperty annotations can be added more convenient for front-end developers to understand the attributes of an object passed in parameters (annotations are added to the properties of the entity Class)

public class Userquerycondition {

    private String username;

    @ApiModelProperty (value = "User Age starting Value")
    private int age;

    @ApiModelProperty (value = "User Age terminated value")
    private int ageto;

    Private String xxx;

    Public String GetUserName () {return
        username;
    }

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

    public int getage () {return age
        ;
    }

    public void Setage (int age) {
        this.age = age;
    }

    public int Getageto () {return
        ageto;
    }

    public void Setageto (int ageto) {
        this.ageto = Ageto;
    }

    Public String getxxx () {return
        xxx;
    }

    public void setxxx (String xxx) {
        this.xxx = xxx;
    }
}
vi. Add @apioperation Annotations to enable front-end developers to understand the functionality of the Controller method for sending HTTP requests (annotations are added to the Controller method)
    @GetMapping
    @JsonView (User.UserSimpleView.class)
    @ApiOperation (value = User Query service) public
    List<user > Query (userquerycondition condition, @PageableDefault (page=2,size=17,sort= "USERNAME,ASC") pageable pageable) {// Use spring's pageable object to get the paging information
        System.out.println (reflectiontostringbuilder.tostring (condition, Tostringstyle.multi_line_style));
        System.out.println (Pageable.getpagesize ());
        System.out.println (Pageable.getpagenumber ());
        System.out.println (Pageable.getsort ());
        list<user> users = new arraylist<> ();
        Users.add (New User ());
        Users.add (New User ());
        Users.add (New User ());
        return users;
    }
@apiparam annotations Allow front-end developers to understand the functionality of incoming generic request parameters (such as String types) (annotations are added to the incoming parameters of the Controller method)
    @GetMapping ("/{id:\\d+}")
    @JsonView (User.UserDetailView.class) public
    User GetInfo (@ApiParam ("User ID") @ Pathvariable String ID) {
        //throw new usernotexistexception (ID);
        SYSTEM.OUT.PRINTLN ("Access to GetInfo Service");
        User user = new user ();
        User.setusername ("Tom");
        return user;
    }
Eight, view the effect of document annotation

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.