Enterprise distributed micro-service Cloud Springcloud springboot MyBatis (25) Integration Swagger2 build restful API

Source: Internet
Author: User
Tags documentation

I. Introduction of dependency

<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>

Second, write Configuration class

@Configuration
@EnableSwagger2 Public
class Swagger2 {

    @Bean public
    Docket Createrestapi () {
        return new Docket (documentationtype.swagger_2)
                . Apiinfo (Apiinfo ()).
                Select ()
                . APIs ( Requesthandlerselectors.basepackage ("Com.forezp.controller"))
                . Paths (Pathselectors.any ())
                . Build ();
    Private Apiinfo Apiinfo () {return
        new Apiinfobuilder ()
                . Title ("Springboot build API Document using Swagger")
                . Description ("Simple and elegant restfun style, Http://blog.csdn.net/forezp")
                . Termsofserviceurl ("Http://blog.csdn.net/forezp ")
                . Version (" 1.0 ")
                . Build ();

By @configuration annotation, it indicates that it is a configuration class, @EnableSwagger2 open Swagger2. Apiinfo () configures some basic information. APIs () specifies that the scanned package will generate the document.

Third, write the production document annotation

Swagger through annotations indicates that the interface generates documents, including interface names, request methods, parameters, return information, and so on. @Api: Modifies the entire class, describing the role of controller @ApiOperation: A method that describes a class, or an interface @ApiParam: a single parameter description @ApiModel: Receiving parameters with objects @ Apiproperty: When parameters are received with an object, a field describing the object @ApiResponse: HTTP response 1 of them are described @ApiResponses: HTTP response Overall description @ApiIgnore: Use this annotation to ignore this API @ Apierror: Error returned information @ApiParamImplicitL: a request parameter @ApiParamsImplicit multiple request parameters

Now with a Li Zilai description:

Package Com.forezp.controller;
Import Com.forezp.entity.Book;
Import Io.swagger.annotations.ApiImplicitParam;
Import Io.swagger.annotations.ApiImplicitParams;
Import io.swagger.annotations.ApiOperation;
Import Org.springframework.ui.ModelMap;
Import org.springframework.web.bind.annotation.*;

Import Springfox.documentation.annotations.ApiIgnore;

Import java.util.*; /** * User to create a book post/books/* user changes to a book Put/books/:id/* user Delete to a book Delete/books/:id/* users get all the books Get/book
 S * User acquires a book Get/books/:id * Created by Fangzhipeng on 2017/4/17. * Official documents: http://swagger.io/docs/specification/api-host-and-base-path/* * @RestController @RequestMapping (value = "/ Books ") public class Bookcontrller {map<long, book> books = Collections.synchronizedmap (new Hashmap<long, B

    Ook> ()); @ApiOperation (value= "Get book list", notes= "get book List") @RequestMapping (value={""}, method= requestmethod.get) public LIST&L T Book> GetBook () {list<book> book = new ArRaylist<> (Books.values ());
    return book; @ApiOperation (value= "Create books", notes= "Create Books") @ApiImplicitParam (name = "book", value = "Books detail entity", required = true, D Atatype = "book") @RequestMapping (value= "", method=requestmethod.post) public String postbook (@RequestBody book Bo
        OK) {Books.put (Book.getid (), book);
    Return "Success"; @ApiOperation (value= "obtained book details", notes= "Get details based on URL id") @ApiImplicitParam (name = "id", value = "id", required = t Rue, DataType = "Long", Paramtype = "path") @RequestMapping (value= "/{id}", method=requestmethod.get) public book GE
    Tbook (@PathVariable Long ID) {return books.get (ID); @ApiOperation (value= "Update Information", notes= "specify update book information according to the ID of the URL") @ApiImplicitParams ({@ApiImplicitParam (name = "id", value = "Book id", required = true, DataType = "Long", Paramtype = "path"), @ApiImplicitParam (name = "Books
    ", value =" book entity ", required = true, DataType =" Books "})@RequestMapping (value= "/{id}", method= requestmethod.put) public String putuser (@PathVariable Long ID, @RequestBody Bo
        Ok book) {Book Book1 = Books.get (ID);
        Book1.setname (Book.getname ());
        Book1.setprice (Book.getprice ());
        Books.put (ID, BOOK1);
    Return "Success"; @ApiOperation (value= "delete book", notes= "specify delete book according to URL id") @ApiImplicitParam (name = "id", value = "Book id", required = t Rue, DataType = "Long", Paramtype = "path") @RequestMapping (value= "/{id}", method=requestmethod.delete) public stri
        Ng DeleteUser (@PathVariable Long id) {books.remove (ID);
    Return "Success"; @ApiIgnore//Use this annotation to ignore this API @RequestMapping (value = "/hi", method = requestmethod.get) public String jsontest
    () {return "Hi you!"; }
}

With relevant annotations, you can let swagger2 generate the appropriate documentation. If you don't need an interface to generate documents, just add @apiignore annotations. It is necessary to note that if the request parameter is on the URL, add paramtype = "path" on the @ApiImplicitParam.

Start Project, visit: http://localhost:8080/swagger-ui.html, you will see Swagger-ui:

The whole integration process is very simple, but I read the relevant information, swagger did not do security protection, may require us to do the relevant work.

Source of Source

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.