Wechat official account: If you have any questions or suggestions, please leave a message on the background. I will try my best to solve your problems.
preface
The Chinese New Year is coming soon. I don’t know when you will take your annual leave. Anyway, I am quite free, so I have time to blog. SpringBoot integration with Swagger2
What is a Swagger2
Swagger is a canonical and complete framework for generating, describing, invoking, and visualizing RESTful Web services.
Why use Swagger2?
I believe that when I was new to Web development, everyone had written Api documents. Handwritten Api documents have the following pain points:
- When a document needs to be updated, another document needs to be sent to the front-end. That is, the communication between document updates is not timely.
- The result returned by the interface is not clear.
- You cannot test the interface directly online, and you usually need to use a tool, such as Postman.
- There are too many interface documents to manage.
These pain points are particularly annoying on large projects where the front and back ends are separated. Swagger2 comes along to address those pain points. Because Swagger2 has the following functions:
- Documents are updated automatically, and as long as the URL of the GENERATED Api remains unchanged, there is little need for front-end communication.
- The interface returns very clear results, including data types, status codes, error messages, and so on.
- You can test documents directly online, and there are instances available for you.
- It only needs one configuration, and then there is an interface document, which is very easy to manage.
Integrated demonstration
How to build a SpringBoot project with IDEA
When building, check Web, LomBok, JPA, and Mysql dependencies in the dependency selection step. Mysql doesn’t have to be checked, because I’m using the actual database here, so I checked it.
The Pom file dependencies after SpringBoot are as follows: Swagger2 version 2.4.0 is used here.
<? xml version="1.0" encoding="UTF-8"? > <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> < modelVersion > 4.0.0 < / modelVersion > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.1.2. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <groupId>com.nasus</groupId> <artifactId>swagger2</artifactId> < version > 0.0.1 - the SNAPSHOT < / version > < name > swagger2 < / name > < description > Demo projectforSwagger2</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> < version > 2.4.0 < / version > < / dependency > < the dependency > < groupId >. IO springfox < / groupId > <artifactId> Springfox-Swagger-ui </artifactId> <version>2.4.0</version> </dependency> </dependencies> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>Copy the code
2. Create a Swagger configuration class in the same directory as the SpringBoot Startup class (Application). Note that the Swagger2 configuration class must be in the same directory as the project entry class (Application).
package com.nasus; 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.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * Project Name:swagger2-demo <br/> * Package Name:com.nasus <br/> * Date:2019/1/22 22:52 <br/> * <b>Description:</b> TODO: Describes what this class does. <br/> * * @author <a href="[email protected]">nasus</a><br/> * Copyright Notice ========================================================= * This file contains proprietary information of Eastcom Technologies Co. Ltd. * Copying or reproduction without prior written approval is Prohibited. * Copyright (c) 2019 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / @ Configuration / / enabled Swagger2 @EnableSwagger2 public class Swagger2 { @Bean public DocketcreateRestApi() {
returnNew Docket (DocumentationType SWAGGER_2)/information/document object apiInfo (apiInfo ()). The select () / / are annotated package path .apis(RequestHandlerSelectors.basePackage("com.nasus.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
returnNew ApiInfoBuilder() // title. Title ("Springboot builds API documents with Swagger"// Api document description.description ("Simple and elegant style of restful, https://blog.csdn.net/turodog/")
.termsOfServiceUrl("https://blog.csdn.net/turodog/".contact(new contact()"Chen Zhiyuan"."https://github.com/turoDog"."[email protected]") // Document version.version ("1.0") .build(); }}Copy the code
Step 3: Configure the annotated Controller class, write the request parameters for each interface, return results, interface description, etc., code as follows:
package com.nasus.controller; import com.nasus.entity.Student; import com.nasus.service.StudentService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import springfox.documentation.annotations.ApiIgnore; /** * Project Name:swagger2-demo <br/> * Package Name:com.nasus.controller <br/> * Date:2019/1/22 22:07 <br/> * <b>Description:</b> TODO: describes the purpose of this class <br/> * * @author <a href="[email protected]">nasus</a><br/>
* Copyright Notice =========================================================
* This file contains proprietary information of Eastcom Technologies Co. Ltd.
* Copying or reproduction without prior written approval is prohibited.
* Copyright (c) 2019 =======================================================
*/
@RestController
@RequestMapping("/student"// @api: modifies the entire class to describe what Controller does.StudentController Api documentation) public class StudentController { @Autowired private StudentService studentService; // @apiOperation: Describes a method of a class, or an interface @apiOperation (value="Get a list of all students", notes="Get a list of all students")
@RequestMapping(value={""}, method= RequestMethod.GET)
public List<Student> getStudent() {
List<Student> list = studentService.findAll();
return list;
}
@ApiOperation(value="Add Student Information", notes="Add Student Information"// @apiIMPLICITParam: a request parameter @apiIMPLICITParam (name ="student", value = Student Details Entity, required = true, dataType = "Student")
@PostMapping("/save")
public Student save(@RequestBody Student student){
return studentService.save(student);
}
@ApiOperation(value="Get student information", notes="Get student details based on the ID of the URL")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer",paramType = "path")
@GetMapping("/{id}")
public Student findById(@PathVariable("id") Integer id){
return studentService.findById(id);
}
@ApiOperation(value="Delete student", notes="Specify the students to be deleted based on the ID of the URL")
@ApiImplicitParam(name = "id", value = "Student ID", required = true, dataType = "Integer",paramType = "path")
@DeleteMapping("/{id}")
public String deleteById(@PathVariable("id") Integer id){
studentService.delete(id);
return "success";
}
@ApiOperation(value="Update student Information", notes="Update student information according to url ID specified"// @apiIMPLICITParams: multiple request parameters @APIIMPLICITParams ({@APIIMPLICITParam (name ="id", value = "Student ID", required = true, dataType = "Integer",paramType = "path"),
@ApiImplicitParam(name = "student", value = "Student entity student", required = true, dataType = "Student")
})
@PutMapping(value="/{id}")
public String updateStudent(@PathVariable Integer id, @RequestBody Student student) {
Student oldStudent = this.findById(id);
oldStudent.setId(student.getId());
oldStudent.setName(student.getName());
oldStudent.setAge(student.getAge());
studentService.save(oldStudent);
return "success"; } // Use this annotation to ignore the API @apiIgnore @requestMapping (value ="/hi", method = RequestMethod.GET)
public String jsonTest() {
return " hi you!"; }}Copy the code
The fourth step, start the project, visit http://localhost:8080/swagger-ui.html address, results are as follows:
Project source code
github
Graphical interface
Swagger2
Value: indicates the interface name. 2. Notes: @APIIMPLICITParam: Used in @apiIMPLICITParams annotations to specify aspects of a request parameter. ParamType: Header: @requestheader 3. Query: @requestParam 4. Path: @pathVariable 5. DataType: parameter type 8. Required: whether the parameter must be passed 9. Value: description of the parameter 10. DefaultValue: defaultValue of the parameter @apiresponses: Used to represent a set of responses @APIResponse: Used in @apiresponses and generally used to express an error response information 1.code: status code 2.message: return custom information 3.response: class that throws an exception @APIignore: @API: Modifates the entire class and describes the Controller's role @APIParam: describes a single parameter @APIModel: receives parameters with an object @APIProperty: When receiving arguments with an object, a field describing the object @APIIgnore: use this annotation to ignore the API @APIError: the message returned by an errorCopy the code
Matters needing attention
The paramType attribute in the @APIIMPLICITParam annotation will affect the interface testing. If the parameter set does not match the spring annotation, the parameter will not be obtained, for example, paramType=path. The function uses @requestParam instead @requestParam = @pathVariable = @pathVariable = @pathVariable = @pathVariable
After the language
The above is my understanding and use of Swagger2. The above is just to teach you how to get started with Swagger2. If you want to use Swagger2 in depth, or you want to consult official documents by yourself. Finally, if you are interested in Python and Java, please long press the QR code to follow the wave. I will try to bring you value. If you think this article is even a little help to you, please help to look good and let more people know.
In addition, after paying attention to send 1024 can receive free learning materials. Python, C++, Java, Linux, Go, front-end, algorithm sharing