Swagger2 common use and Springboo integration Swagger2

Source: Internet
Author: User

Several pain points for the Handwriting API documentation:

    1. Documents need to be updated, you need to send a copy to the front end, that is, the document update communication is not timely.
    2. Ambiguous interface return result
    3. Interfaces cannot be tested directly online, often using tools such as Postman
    4. Too many interface documents, bad management

Swagger is in order to solve this problem, of course, can not say that swagger must be perfect, of course, there are shortcomings, the most obvious is the code to move more strongly.

Here is the Springboot integration Swagger2, the way to generate interface documents directly.

One, dependence
<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, Swagger configuration class

It is important to note that the API file is configured inside the path of the controller package, otherwise the resulting document will not scan the interface.

Import io.swagger.annotations.ApiOperation;

Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;

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;

/**
* @author XXY
* @Description
* @date 2018-01-23 22:12:31
*/
@Configuration
public class Swagger2 {

@Bean
Public Docket Createrestapi () {
return new Docket (documentationtype.swagger_2)
. Apiinfo (Apiinfo ())
. Select ()
. APIs (Requesthandlerselectors.basepackage ("Com.aisino.projects.task.web"))
. APIs (Requesthandlerselectors.withmethodannotation (Apioperation.class))
. Paths (Pathselectors.any ())
. build ();
}

Private Apiinfo Apiinfo () {
return new Apiinfobuilder ()
. Title ("Springboot using swagger to build API documentation")
. Description ("Simple and elegant restfun style, http://blog.csdn.net/saytime")
. Termsofserviceurl ("Http://blog.csdn.net/saytime")
. Version ("1.0")
. build ();
}
}

Third, open the swagger
Application.class Plus annotation @enableswagger2 means open swagger
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.springbootapplication;import Springfox.documentation.swagger2.annotations.EnableSwagger2;  @SpringBootApplication  @EnableSwagger2 public class  springbootswagger2application {public static void main (string[] args) {Springapplication.run (Springbootswagger2application. 


access
address
Span style= "font-size:16px" >:http://127.0.0.1:8080/app/swagger-ui.html
Iv. General Usage

Example 1:

/**
* Login-Get user
* @return
*/
@ApiOperation (value= "User Login", HttpMethod = "POST", notes= "login, enter username, password")
@ApiImplicitParams ({
@ApiImplicitParam (paramtype = "Query", name = "Username", value = "username", required = true, DataType = "String"),
@ApiImplicitParam (paramtype = "Query", name = "Password", value = "password", required = true, DataType = "String")
})
@RequestMapping (value= "/login", method= requestmethod.post)
@ResponseBody
Public String Login (httpservletrequest request, string username,string password) {
Retobj retobj = new Retobj ();
Retobj.setflag (FALSE);
try {
String password = base64.getfrombase64 (User.getpassword ());
User.setpassword (Cryptutils.byte2hex (Cryptutils.encrypt (Login_key,password.getbytes ("UTF-8")));
Shoptaskuser userInfo = userservice.getuserinfo (user);
if (userInfo! = null) {
Request.getsession (). SetAttribute ("Shoptaskusermodel", userInfo);
Retobj.setflag (TRUE);
Logger.info (Userinfo.getusername () + "Login successful! ");
}
} catch (Exception e) {
E.printstacktrace ();
}
Return json.tojsonstring (retobj);
}

Example 2:

@ApiOperation (value = "Query invoice information", HttpMethod = "POST", notes = "Invoice information for fast invoicing based on tax number")
@ApiImplicitParam (paramtype = "Query", name = "Taxnum", value = "Enterprise Tax number", required = true, DataType = "String")
@RequestMapping (value = "/queryinvoiceinfo.do")
@ResponseBody
public string Queryinvoiceinfo (string taxnum) {
if (Commonutil.isblank (Taxnum)) {
Return json.tojsonstring (Commonutil.returnmap (jfreturnenum.param_missing,null));
}
Log.info ("Valetordercontroller queryinvoiceinfo parameter taxnum:" +taxnum);
Invoicevo Invoicevo = Valetorderservice.queryinvoiceinfo (taxnum);
Return json.tojsonstring (Commonutil.returnmap (Jfreturnenum.success,invoicevo));
}

Example 3:

@ApiOperation (value = "Save receipt Information", HttpMethod = "POST", notes = "Save Receipt Information")
//@ApiImplicitParam (name = "Receivinginfov O ", value =" Receipt address information ", required = true, DataType =" Receivinginfovo ")
@RequestMapping (value ="/savereceivinginfo.do ")  br> @ResponseBody
Public String savereceivinginfo (@ApiParam @RequestBody Receivinginfovo Receivinginfovo) {
Log.info ("Valetordercontroller savereceivinginfo parameter Receivinginfovo:" +json.tojsonstring (ReceivingInfoVO));
Boolean updateres = Valetorderservice.savereceivinginfo (Receivinginfovo);  
if (!updateres) {
return json.tojsonstring (Commonutil.returnmap (Jfreturnenum.fail,null));
}
Return Json.tojsonstring (Commonutil.returnmap (jfreturnenum.success,null));
}

public class Receivinginfovo {
@ApiModelProperty (value = "Order Number")
Private String OrderNo;
@ApiModelProperty (value = "Consignee name")
Private String Consigneename;
@ApiModelProperty (value = "Consignee mobile number")
Private String Consigneephone;
@ApiModelProperty (value = "Delivery address area + Detailed address")
Private String adress;
.........

}

Swagger2 common use and Springboo integration 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.