Spring Boot (4) consolidates swagger to operate the API

Source: Internet
Author: User

1.pom.xml

<!--swagger2-restful API documentation--        <dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox-swagger2</artifactId>            <version>2.6.1</version>        </ dependency>        <dependency>            <groupId>io.springfox</groupId>            <artifactId> springfox-swagger-ui</artifactid>            <version>2.6.1</version>        </dependency>

2.application.java

Package Com.guilf;import Org.springframework.boot.springapplication;import org.springframework.boot.autoconfigure.springbootapplication;/** * Note: The startup class should not be placed in the Main/java root directory, startup will be error */@ Springbootapplicationpublic class Application {public    static void Main (string[] args) {        Springapplication.run (Application.class,args);}    }

3.swaggerconfig.java

Package Com.guilf;import Com.google.common.base.predicate;import Org.springframework.boot.autoconfigure.web.basicerrorcontroller;import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.configuration;import Org.springframework.web.bind.annotation.responsebody;import Org.springframework.web.bind.annotation.restcontroller;import Springfox.documentation.requesthandler;import Springfox.documentation.builders.apiinfobuilder;import Springfox.documentation.builders.pathselectors;import Springfox.documentation.builders.requesthandlerselectors;import Springfox.documentation.service.apiinfo;import Springfox.documentation.spi.documentationtype;import Springfox.documentation.spring.web.plugins.docket;import Springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @enableswagger2//Enable Swaggerpublic Class Swaggerconfig {@Bean public Docket Createrestapi () {/** * swagger will default to Requestmap in all controllers The Ping method generates APIs, and in fact we generally onlyYou need a standard interface (like the Controller method that returns a page we don't need), * all you can do is to set the requirements for the method to generate the API as follows. * Following my Restcontroller annotated class and responsebody annotation methods to generate Swaager APIs, and exclude specific classes */predicate<requesthandler> pred Icate = new Predicate<requesthandler> () {public boolean apply (RequestHandler input) {Cla                ss<?> Declaringclass = Input.declaringclass ();                if (Declaringclass = = Basicerrorcontroller.class)//exclude return false;                if (Declaringclass.isannotationpresent (Restcontroller.class))//Annotated class return true;                if (Input.isannotatedwith (Responsebody.class))//annotated method return true;            return false;        }        }; return new Docket (documentationtype.swagger_2). Apiinfo (Apiinfo ()). Usedefaultresponsemessag          Es (FALSE). Select (). APIs (predicate)//The scope that the API generates is set here in two ways:       1. Above through custom filter rules//2, by defining the package path that requires the API to be generated//.apis (S    wagger_scan_base_package)). Build ();                } private Apiinfo Apiinfo () {return new Apiinfobuilder (). Title ("Service of User Information Interface")//Big title    . Version ("1.0")//version. Build (); }}

4.user.java

Package Com.guilf.domain;public class User {    private String ID;    private String name;    Private Integer age;    Public String getId () {        return ID;    }    public void SetId (String id) {        this.id = ID;    }    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }    Public Integer Getage () {        return age;    }    public void Setage (Integer age) {        this.age = age;    }}

5.userapicontroller.java

Package Com.guilf.mvc;import Io.swagger.annotations.apiimplicitparam;import Io.swagger.annotations.apiimplicitparams;import Io.swagger.annotations.apioperation;import Org.springframework.web.bind.annotation.*;import com.guilf.domain.user;import java.util.*;/** * @ClassName:  Userapicontroller * @Description: (using Swagger display API) * * @version v1.1 */@RestController @requestmapping ("/users") public Class Userapicontroller {static map<string, user> users = Collections.synchronizedmap (new hashmap<string, Us    Er> ()); @ApiOperation (value = "Get user list", notes = "") @RequestMapping (value = "/", method = requestmethod.get) public list<use R> getuserlist () {//Processing "/users/" GET request, used to get the user list//can also be passed by @requestparam from the page parameters to query the condition or the transfer of page information list        <User> u = new arraylist<> (Users.values ());    return u; } @ApiOperation (value= "Create user", notes= "create user according to User object") @ApiImplicitParam (name = "User", value = "Users detail entity user", required = True, DataType = "User") @RequestMapping (value= "/", method=requestmethod.post) public String postuser (@ModelAttribute user user) {/ /processing "/users/" POST request, used to create user//In addition to @modelattribute binding parameters, you can also pass parameters Users.put (User.getid () from the page via @requestparam,        user);    Return "Success"; } @ApiOperation (value= "Get user Information", notes= "get corresponding user information based on User ID") @ApiImplicitParams (@ApiImplicitParam (name = "id", value = "User ID ", required = True,datatype =" String ")) @RequestMapping (value="/{id} ", method=requestmethod.get) public User Getuse         R (@PathVariable String ID) {//handle '/users/{id} ' Get request to get user information for ID value in URL//ID in URL can be @pathvariable bound to function parameter    return Users.get (ID); } @ApiOperation (value = "Modify user Information", notes = "Modify corresponding user information based on User ID") @ApiImplicitParams ({@ApiImplicitParam (name = "id", value = " User ID ", required = True,datatype =" String "), @ApiImplicitParam (name =" User ", value =" Users entity object ", require D = true,datatype = "User")}) @RequestMapping (value= "/{id}", Method=requestmethod.put) public string Putuser (@PathVariable string ID, @ModelAttribute user user) {//Handle PUT Request for "/users/{id}"        To update the user information user U = users.get (id);        U.setname (User.getname ());        U.setage (User.getage ());        Users.put (ID, u);    Return "Success"; } @ApiOperation (value = "Get user Information", notes = "Delete corresponding user information based on User ID") @ApiImplicitParam (name = "id", value = "User id", required = TR Ue,datatype = "string") @RequestMapping (value= "/{id}", method=requestmethod.delete) public String deleteuser (@PathVa        Riable String ID) {//Processing "/users/{id}" delete request, used to delete user users.remove (ID);    Return "Success"; }}

6. Start, y page display

Http://localhost:8088/swagger-ui.html

7. Add, insert data point try it out

8. Click to view

Spring Boot (4) consolidates swagger to operate the API

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.