SpringBoot-- integrated swagger2

Turn: https: //www.cnblogs.com/lenve/p/11756725.html

Before and after the end of the separation, maintenance interface documentation is basically indispensable.

Ideally after a good design, interface documentation sent to the front and rear, and everyone in accordance with established rules of their development, the development of good can be more than a butt on the line. Of course, this is an ideal state, the actual development is rarely encountered such a situation, the interface is always in constant change, change is necessary to maintain, has done little friends know about it there what a big head! Fortunately, there are some tools can reduce our workload, Swagger2 is one of them, as for other similar software functionality but charges here do not introduce too much. In this paper, and everyone to chat at how to integrate Swagger2 in Spring Boot in.

Project Creation

Of course, the first is to create a Spring Boot project, adding web dependency, create success, adding two Swagger2 related to dependence, full dependence as follows:

<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>
</dependency>

Swagger2 Configuration

Swagger2 configuration is also relatively easy, after the project is created, developers only need to provide a Docket himself to Bean, as follows:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("org.javaboy.controller"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger")
                        .description("SpringBoot整合Swagger,详细信息......")
                        .version("9.0")
                        .contact(new Contact("啊啊啊啊","blog.csdn.net","[email protected]"))
                        .license("The Apache License")
                        .licenseUrl("http://www.javaboy.org")
                        .build());
    }
}

Provide here a configuration class, first enable Swagger2 by @ EnableSwagger2 annotation, and then configure a Docket Bean, the Bean, the mapping between the path and to scan the location of the connector in apiInfo, the information Swagger2 documentation Web site of the main configuration bit, for example sites the title, site description, contact information, the protocol used, and so on.

So, Swagger2 even if the configuration is successful, and very convenient.

At this time the project started, input  http://localhost:8080/swagger-ui.html, see the following page, indicating that the configuration has been successful:

Creating interfaces

The next step is to create the interfaces, Swagger2 related notes is not much, but it is easy to understand, here I come to the small partners illustrate respectively:

@RestController 
@Api (Tags = "User Management interfaces" ) 
@RequestMapping ( "/ User" )
 public  class the UserController { 
    @PostMapping ( "/" ) 
    @ApiOperation ( "add user interface" ) 
    @ApiImplicitParams ({ 
            @ApiImplicitParam ( name = "username", value = "username", defaultValue = "John Doe" ), 
            @ApiImplicitParam (name = "address", value = "user address", defaultValue = "Shenzhen", required = to true ) 
    }) 
    public RespBean addUser (String username,@RequestParam(required = true) String address) {
        return new new RespBean (); 
    } 
    @GetMapping ( "/" ) 
    @ApiOperation ( "The user interface of the query id" ) 
    @ApiImplicitParam (name = "id", value = "user id", defaultValue = "99", required = to true )
     public the user getUserById (@PathVariable Integer id) { 
        the user user = new new the user (); 
        user.setId (id); 
        return user; 
    } 
    @PutMapping ( "/ {id}" ) 
    @ApiOperation ( "the user interface update id ")
    public User updateUserById(@RequestBody User user) {
        return user;
    }
}

This side involves multiple API, I'll explain to the small partners are:

  1. @Api annotation can be used to mark the current functions of the Controller.
  2. @ApiOperation annotation method for marking a role.
  3. @ApiImplicitParam annotation is used to describe a parameter, the parameter can be configured in Chinese meaning, you may also set a default value to the parameter, to avoid manual input at the time of testing the interface.
  4. If there are multiple parameters, it is necessary to describe the use of a plurality of @ApiImplicitParam annotations, annotation needs to be placed a plurality @ApiImplicitParam @ApiImplicitParams annotation.
  5. Note that, @ ApiImplicitParam annotation Although you can specify parameters are mandatory, but it can not replace @RequestParam (required = true), the former required only within the framework required Swagger2, abandoned Swagger2, this restriction is no with, so if a developer needs to specify the parameters required, @RequestParam (required = true) annotation or can not be omitted.
  6. If the parameter is an object (e.g., update interface supra), the description of the parameters may also be placed in the entity classes. For example, the following piece of code:
@ApiModel
public class User {
    @ApiModelProperty(value = "用户id")
    private Integer id;
    @ApiModelProperty(value = "用户名")
    private String username;
    @ApiModelProperty(value = "用户地址")
    private String address;
    //getter/setter
}

Well, after the above configuration, the next, just refresh the page that opens, you can see the following effect:

You can see that all the interfaces are listed here, including a request mode, the interface address and the name of the interface to the other point to open a port, you can see the following information:

You can see, parameters, parameter requirements, the default parameter values, etc. are all out to show the interface, query under the parameter type parameter to indicate  key/value the form of transfer, top right, click Try it out, you can interface testing:

Click the Execute button to indicate that the request is sent for testing. The test results will show below the Response.

Small partners noted, the following query type parameter passed as a parameter indicative of key / value, the value may also be where body, body parameter indicating the way to request transfer body, such as updating the above interfaces, as follows:

Another possibility is of course is a path parameter herein, represents a parameter in the transmission path, for example according to a query interface to the user id:

Of course, in addition to these, there are some notes response values ​​are relatively simple, small partners can find their own way down.

In the Security Configuration

If our Spring Boot project integrates Spring Security, if you do not do additional configuration, Swagger2 document may be intercepted, this time only need to rewrite configure methods to configure Spring Security's class, add the following filters to:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers("/swagger-ui.html")
            .antMatchers("/v2/**")
            .antMatchers("/swagger-resources/**");
}

So after, Swagger2 files you do not need certification will be able to visit.

Guess you like

Origin www.cnblogs.com/jvStarBlog/p/11762781.html