Springboot | Tenth chapter: Integration and use of Swagger2

Source: Internet
Author: User

Objective

The previous section describes the mybatisPlus integration and ease of use, and this chapter begins with the integration of the user tables in the previous section Swagger2 . Now all the 前后端分离 development and micro-services to the road, sub-service and separation of the front and rear end of the development of the communication costs increased. So a powerful RESTful API document is essential. And at present in the back-end field, basically is Swagger the world.

    • Swagger2 Introduction
    • Springboot Integration
    • Swagger Access and use
    • Swagger common Property Descriptions
    • Summarize
    • At last
    • Cliché
Swagger2 Introduction

Swaggeris an RESTful interface of the document online automatic generation, functional testing function framework. A canonical and complete framework for building, describing, invoking, and visualizing RESTful the style of Web services, plus swagger-ui , can be well presented.

Springboot Integration

The swagger version chosen here is: 2.8.0

0.pom Dependency

    <!--swagger -->    <dependency>        <groupId>io.springfox</groupId>        <artifactId>springfox-swagger2</artifactId>        <version>2.8.0</version>    </dependency>    <dependency>        <groupId>io.springfox</groupId>        <artifactId>springfox-swagger-ui</artifactId>        <version>2.8.0</version>    

1. Writing the configuration file (Swagger2config.java)

The main is to add annotations @EnableSwagger2 and defined Docket bean classes.

 @EnableSwagger2 @configurationpublic class Swaggerconfig {//Whether the swagger is turned on, the formal environment is generally closed and can be set according to the multi-environment configuration of Springboot @Value (Value = "${swagger.enabled}") Boolean swaggerenabled; @Bean Public Docket Createrestapi () {return new docket (documentationtype.swagger_2). Apiinfo (Apiinfo ()) Whether to open the. Enable (swaggerenabled). Select ()//scanned path package. APIs (RequestHandle Rselectors.basepackage ("Cn.lqdev.learning.springboot.chapter10"))//Specify Path processing Pathselectors.any () to represent all paths . Paths (Pathselectors.any ()). Build (). Pathmapping ("/"); } private Apiinfo Apiinfo () {return new Apiinfobuilder (). Title ("Springboot-swagger2 Integration and use-demo example "). Description (" Okong | Staggered's Ape ")//author information. Contact (" Okong "," https://blog.lqdev.cn/"," [Email protecte D]). Version ("1.0.0"). Build (); }}

3. Add the contents of the document (usually in the Controller , request parameters on the annotation, where the above chapters are UserController configured)

UserController

/** * User Control layer Simple demo add and delete changes and pagination * Added swagger document content 2018-07-21 * @author Okong * * * * @RestController @requestmapping ("/user") @Api (tags=        "User API") public class Usercontroller {@Autowired iuserservice userservice;    @PostMapping ("Add") @ApiOperation (value= "User new")//normal business, you need to do transaction control in the user class, the control layer is generally not business control. @Transactional (rollbackfor = exception.class) public map<string,string> addUser (@Valid @RequestBody userreq US        Erreq) {User user = new User ();        User.setcode (Userreq.getcode ());        User.setname (Userreq.getname ());        Because the primary key policy ID is set,//user.setid (0L) is automatically generated without assigning a value.        Userservice.insert (user);        map<string,string> result = new hashmap<string,string> ();        Result.put ("Respcode", "01");        Result.put ("Respmsg", "new success");        Transaction Test//SYSTEM.OUT.PRINTLN (1/0);    return result; } @PostMapping ("Update") @ApiOperation (value= "user modified") Public map<string,string> updateUser (@Valid @R EquestbOdy Userreq userreq) {if (Userreq.getid () = = NULL | |        ". Equals (Userreq.getid ())) {throw new commonexception (" 0000 "," Update ID cannot be empty ");        User user = new user ();        User.setcode (Userreq.getcode ());        User.setname (Userreq.getname ());                User.setid (Long.parselong (Userreq.getid ()));        Userservice.updatebyid (user);        map<string,string> result = new hashmap<string,string> ();        Result.put ("Respcode", "01");        Result.put ("Respmsg", "update Success");    return result; } @GetMapping ("/get/{id}") @ApiOperation (value= "user query (ID)") @ApiImplicitParam (name= "id", value= "Query id", Requi red=true) public map<string,object> getUser (@PathVariable ("id") String ID) {//query user user = Userse        Rvice.selectbyid (ID);        if (user = = null) {throw new Commonexception ("0001", "User id:" + ID + ", not Found"); } Userresp resp = Userresp.builder (). ID (User.getid (). TostriNg ()). Code (User.getcode ()). Name (User.getname ()). Status (User.getstatus ())        . build ();        map<string,object> result = new hashmap<string,object> ();        Result.put ("Respcode", "01");        Result.put ("Respmsg", "success");        Result.put ("Data", resp);    return result; } @GetMapping ("/page") @ApiOperation (value= "user query (Paging)") public map<string,object> pageuser (int c        urrent, int size) {//paging page<user> page = new Page<> (current, size);        map<string,object> result = new hashmap<string,object> ();        Result.put ("Respcode", "01");        Result.put ("Respmsg", "success");        Result.put ("Data", Userservice.selectpage (page));    return result; }        }

UserReq.java

@Data@Builder@NoArgsConstructor@AllArgsConstructor//加入@ApiModel@ApiModelpublic class UserReq {        @ApiModelProperty(value="ID",dataType="String",name="ID",example="1020332806740959233")    String id;        @ApiModelProperty(value="编码",dataType="String",name="code",example="001")    @NotBlank(message = "编码不能为空")    String code;        @ApiModelProperty(value="名称",dataType="String",name="name",example="oKong")    @NotBlank(message = "名称不能为空")    String name;}
Swagger Access and use

API Home Path: http://127.0.0.1:8080/swagger-ui.html

Debug: Click on the list of APIs you need to access, click the try it out! button, you can pop up the page:

Perform:

Results:

You can download the sample to see where the custom characters appear, so you can get a general idea of where the fields are going to be.

Swagger common Property Descriptions
function Range API Use location
Object Properties @ApiModelProperty Used on fields in the Access parameter object
Protocol Set Description @Api For the Controller class
Protocol description @ApiOperation Used in the controller's method.
Response Set @ApiResponses Used in the controller's method.
Response @ApiResponse Used in the @ApiResponses inside
Set of non-object parameters @ApiImplicitParams Used in the controller's method.
Non-object parameter description @ApiImplicitParam Used in the @apiimplicitparams method.
Describe the meaning of the returned object @ApiModel Used on the Return object class

Commonly used annotations,, @Api @ApiOperation @ApiModel and @ApiModelProperty examples are labeled, for other annotations, we can automatically Google, after all, the usual on these several. swaggerafter that, some post of the original requests need postman such debugging tools to launch, and now directly on the page can be debugged, is not very cool! For the service callers, with this API document is also at a glance, do not need and backend how much communication costs, according to the API instructions for the front-end development.

Summarize

This chapter is mainly for Swagger the integration and simple use of the description, detailed usage, can be self-search for relevant information, here is not elaborated. Because the document requirements above 80% are basically satisfied. Some, such as the front-end based on the swagger api-docs rapid development of the front end, which requires actual practice, such as the rapid generation of form pages, and so is also very convenient things. Finally, it is strongly recommended to shut swagger down the production environment to avoid unnecessary vulnerability exposure!

At last

At present, many big guys on the internet have a SpringBoot series of tutorials, if there is a similar, please forgive me. This article is the author in front of the computer word knocking, each step is practice. If there is something wrong in the text, also hope to put forward, thank you.

Cliché
    • Personal QQ:499452441
    • Public Number:lqdevOps

Personal blog: https://blog.lqdev.cn

Complete Example: chapter-10

Original address: http://blog.lqdev.cn/2018/07/21/springboot/chapter-ten/

Springboot | Tenth chapter: Integration and use of Swagger2

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.