Abstract: In project development, it is often expected to be separated from the front and back ends, that is, back end developers often need to output a large number of service interfaces. Whether it is Java or PHP and other languages, the interface provider often needs to spend a certain amount of effort to write interface documents, such as the address of the A interface, the parameter situation that needs to be passed, the JSON data format of the return value, and the description of each field. Of course, it also needs to consider HTTP request headers, request content and other information. As the project progresses rapidly and iterates rapidly, the interfaces output by the backend often face problems such as modification and repair, which also means that the interface documents must also be adjusted accordingly. The maintenance and readability of interface documents are greatly reduced.
Since the interface document requires energy maintenance and appropriate face-to-face communication, why don’t we think of a solution? First: you don’t need to write interface documents; Second: When the front-end and back-end communicate interface problems, can the back-end provide a URL? List all the service interfaces that can be called in this URL, and list the parameters and the return value description in each service interface. Third: If the back-end interface can simulate calls, all problems will be solved. In this article, we will focus on explaining the integrated Swagger2 framework in Sringboot.
1.1. Add Swagger2 dependency
Add the following dependencies to the project's pom.xml file.
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version></dependency><dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version></dependency>
First, we need to create a startup class, the code is as follows:
@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Then create a new configuration class for swagger2 in the same level directory of the above class as follows:
@Configuration@EnableSwagger2public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.shareniu.web")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Follow Share Niu to learn Springboot Source Code Analysis Series Courses") .description("For more Spring Boot related articles, please follow Share Niu's Blog") .termsOfServiceUrl("http://www.shareniu.com/") .contact("Niu") .license("Copyright 2017-2018 Share Niu") .version("1.0") .build(); }}@Configuration has formulated that spring should load this class, and @EnableSwagger2 annotation should enable the Swagger function.
The ApiInfo in the above will eventually be displayed on the front end. We use the scanning package to configure the configuration, that is, RequestHandlerSelectors.basePackage. The controllers in this package and the subpackage ultimately generate API documents. (Except for requests specified by @ApiIgnore annotation).
1.2. Added documentation instructions
After the above class declaration, we can actually call it directly, but in order to increase the readability of the document, we still need to add some instructions to the interface. Let's write a controller first as follows:
@RestController@RequestMapping(value="/users")public class UserController { static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>()); static { User user = new User(); user.setAge(18); user.setId(1L); user.setName("aa"); users.put(1L, user); } @ApiOperation(value="get all user list", notes="") @RequestMapping(value={""}, method=RequestMethod.GET) public List<User> getUserList() { List<User> r = new ArrayList<User>(users.values()); return r; } @ApiOperation(value="Create a new user", notes="Create a user from the User object") @ApiImplicitParam(name = "user", value = "User detailed entity user", required = true, dataType = "User") @RequestMapping(value="", method=RequestMethod.POST) public String postUser(@RequestBody User user) { users.put(user.getId(), user); return "success"; } @ApiOperation(value="get user details", notes="get user details based on the id of the url") @ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "Long") @RequestMapping(value="/{id}", method=RequestMethod.GET) public User getUser(@PathVariable Long id) { return users.get(id); } @ApiOperation(value="Update user details", notes="Specify update object according to url id") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "User ID", required = true, dataType = "Long"), @ApiImplicitParam(name = "user", value = "User detailed entity user", required = true, dataType = "User") }) @RequestMapping(value="/{id}", method=RequestMethod.PUT) public String putUser(@PathVariable Long id, @RequestBody User user) { User u = users.get(id); u.setName(user.getName()); u.setAge(user.getAge()); users.put(id, u); return "success"; } @ApiOperation(value="Delete existing users", notes="Specify the delete object according to the id of the url") @ApiImplicitParam(name = "id", value = "User ID", required = true, dataType = "Long") @RequestMapping(value="/{id}", method=RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { users.remove(id); return "success"; }} @ApiOperation: Used to describe the function of this interface. This annotation can explain the responsibilities of the interface, the return header information, the request method of the method ("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"), protocol (http, https, ws, wss), and http status code.
@ApiImplicitParam: Used to add descriptions to parameters. You can set the name of the parameter, whether it is a required item, the description information of the parameter, whether it is read-only, etc.
After the above code is submitted, start springboot and visit http://127.0.0.1:8080/swagger-ui.html as shown in the figure below:
The above picture is divided into two parts. The upper part is configured through the Swagger2 class, and the lower part is the interface document in the UserController class.
Here we use /user as an example to illustrate:
Click /user as shown in the following figure:
The yellow spot above shows the sample data returned by this interface. That is, the data structure of the User. Response Content Type: The header information returned by the interface. Click Try it out. As shown below:
The Baody, code, and response headers returned by this interface have been successfully returned.
Summarize
The above is the method of integrating the Swagger2 framework in Springboot introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!