About how to integrate Swagger2 in SpringBoot (pro test & & with source code)
1.1 Preface
Recently, I learned SpringBoot from the guide of SpringBoot 2 textbook collection by teacher Wang song, which happens to be about SpringBoot integrating Swagger2. I happened to see this part of the guide and found that the case could not work as expected due to the iteration of the SpringBoot version. Then I will explain the pit I stepped on and how to integrate SpringBoot into Swagger2 by consulting relevant materials, hoping to bring help to you.
2.1 what is Swagger?
In the past, API documents were often defined by background developers. Sometimes, due to the modification of an API definition, the documents were not updated in time, which would lead to the inconsistency between the front-end personnel and the back-end API documents, which would make the communication cost and cost very high. Swagger is a normative and complete framework for generating, describing, invoking and visualizing RESTful Web services. API documents are the best way to communicate in the development mode of front-end and back-end separation. Swagger has four characteristics, 1 Timeliness: timely and accurately notify relevant front-end personnel after interface changes; 2. Normalization: ensure the normalization of the interface, such as interface address, request mode, parameters, response format and error information; 3. Consistency (the interface information is consistent, and there will be no differences due to the inconsistent version of the document obtained by the developer); 4. Testability: interface testing can be carried out directly on the interface document.
3.1 start integration
3.1.1 create a SpringBoot project and open it in pom Add the dependency of Swagger2 to the XML.
<!-- solve maven introduce swagger For the version problems caused by dependency, the following two packages should be Swagger2 Above the package, i.e. 1.5.20 Version needs to be 1.5.21 cover --> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.21</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>1.5.21</version> </dependency> <!-- introduce Swagger2 Support for --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.5.6</version> </dependency>
Note: the above steps ignore the process of creating a project. Pom The spring boot starter parent version under the XML file needs to be modified to a jar package below version 2.6.0, which can be used with version 2.5.0. (default from SpringBoot official website: https://start.spring.io/ The version pulled down is 2.7.1)
3.1.2 configure Swagger2
@Configuration @EnableSwagger2 //1. Enable Swagger2 public class SwaggerConfig { public static final String SWAGGER_SCAN_BASE_PACKAGE="com.itnice.springbootswagger2.controller"; @Bean public Docket createRestApi(){ //2. Configure a Docket Bean. In this Bean, configure the mapping path and the location of the interface to be scanned. In apiInfo, //Mainly configure Swagger2 document website information, such as website title, website description, contact information, and protocol used return new Docket(DocumentationType.SWAGGER_2). //Whether to enable (true enable false hide. It is recommended to hide in the production environment) //.enable(false) pathMapping("/") .select() .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE)) .paths(PathSelectors.any()) .build().apiInfo(apiInfo()); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("SpringBoot integration Swagger") .description("SpringBoot integration Swagger,detailed information.....") .version("1.0") .contact(new Contact("Ow, ow","blog.csdn.net","455164325@qq.com")) .license("The Apache License") .licenseUrl("http://www.baidu.com") .build(); }
Code interpretation: change SwaggerConfig into a Configuration class through @Configuration. First, enable Swagger2 through the @EnableSwagger2 annotation, and then configure a Docket Bean. In this Bean, configure the mapping path and the location of the interface to be scanned. In apiInfo, mainly configure Swagger2 document website information, such as website title, website description, contact information, protocol used, etc.
3.1.3 create interface
@RestController @RequestMapping("/user") @Api(value = "Test interface",tags = "User management related interfaces") public class UserController { /** * Save user data * @param user * @return */ @PostMapping("/save") //Method parameter description, name parameter name; value parameter description, remarks; dataType parameter type; Whether required is required. The default is false; //@ApiOperation(value = "interface description", httpMethod = "interface request method", // response = "interface return parameter type", notes = "interface release description"; @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "User number",required = true), @ApiImplicitParam(name = "username", value = "user name",required = true), @ApiImplicitParam(name = "address", value = "User address") }) @ApiOperation(value = "Add user",httpMethod ="POST",response =String.class,notes = "Add user") public String saveUser(User user){ return "User saved successfully!"; } @GetMapping("/findUserById") @ApiImplicitParam(name="id",value = "User number",required = true) @ApiOperation(value = "According to users id Find the specified user",httpMethod ="GET",response =User.class,notes = "According to users id Find the specified user") public User getUserById(int id){ return new User(); } @GetMapping("/removeUserById") @ApiImplicitParam(name="id",value = "User number",required = true) @ApiOperation(value = "According to users id Delete specified user",httpMethod ="GET",response =String.class,notes = "According to users id Delete specified user" ) public String deleteUserById(int id){ return "User saved successfully!"; }
Code interpretation:
@Api annotations can be used to mark the functions of the current Controller.
@The ApiOperation annotation is used to mark the role of a method.
@ApiImplicitParam annotation is used to describe a parameter. The Chinese meaning of the parameter can be configured, and the default value can be set for the parameter, so that manual input can be avoided during interface testing.
If there are multiple parameters, you need to use multiple @ApiImplicitParam annotations to describe them, and multiple @ApiImplicitParam annotations need to be placed in one @ApiImplicitParams annotation.
It should be noted that although the @ApiImplicitParam annotation can specify that the parameter is mandatory, it cannot replace @RequestParam(required = true). The former is mandatory only within the framework of Swagger2. This restriction is useless if Swagger2 is abandoned. Therefore, if the developer needs to specify a parameter to be mandatory, @RequestParam(required = true) annotation cannot be omitted.
If the parameter is an object (such as the update interface above), the description of the parameter can also be placed in the entity class. For example, the following code:
@ApiModel public class User { @ApiModelProperty(value = "user id") private int id; @ApiModelProperty(value = "user name") private String username; @ApiModelProperty(value = "User address") private String address; //Omit get/set method }
3.1.4 start the project and visit: http://localhost:8080/swagger-ui.html can access swagger normally. The page is as follows:
Note: in addition to being used as API documents, Swagger can also be used for interface testing. You can use the "Try it out" button on the interface to conduct interface testing.
4.1 step on the pit during integration and avoid the pit
1. Problem 1. After starting the project because the SpringBoot version is too high, visit localhost:8080/swagger-ui The HTML page appears 404.
Solution: pom The version of spring boot starter parent in XML has been reduced to less than 2.6.0, and the pro test (2.5.0) version is available.
2. Question 2 visit swagger ui HTML background error (swagger error), error description: WARN i.s.m.p.AbstractSerializableParameter - [getExample,421] - Legal DefaultValue null.
Cause of the problem: maven introduced the problem of swagger dependency. Swagger annotations, which swagger depends on, is 1.5.20, while the required version is 1.5.21.
Solution: directly modify pom dependency: under the same path length, whoever declares first takes priority. Put 1.5.21 on it to exclude the 1.5.20 version of springfox-swagger2 dependency.
5.1 project source code address (Gitee)
https://gitee.com/brave_zeng/SpringBootSwagger2
6.1 extended knowledge, configuration in Security
If Spring Security is integrated into our Spring Boot project, Swagger2 documents may be intercepted without additional configuration. At this time, you only need to rewrite the configure method in the configuration class of Spring Security and add the following filter:
@Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers("/swagger-ui.html") .antMatchers("/v2/**") .antMatchers("/swagger-resources/**"); }
7.1 references
Spring Boot2 tutorial collection
SpringBoot integrates Swagger2 (full version)
Question 2