After the front and back ends are separated, maintaining interface documentation is essentially a necessity.

An ideal state is that after the design is good, the interface document is sent to the front end and back end, everyone according to the established rules of their own development, development and docking can be online. Of course, this is a very ideal state, but the actual development rarely encountered such a situation, the interface is always in constant change, there are changes to maintain, do friends know how big this matter! Thankfully, Swagger2 is one of a number of tools available to ease our workload, but we won’t go into too much detail on other apps that do similar things but charge for them. How to integrate Swagger2 in Spring Boot

Engineering to create

Swagger2 dependency = Swagger2 dependency = Swagger2 dependency = Swagger2 dependency = Swagger2 dependency = Swagger2 dependency = Swagger2 dependency = Swagger2 dependency = Swagger2 dependency = Swagger2 dependency = Swagger2 dependency

<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>
Copy the code

Swagger2 configuration

The configuration of Swagger2 is also easy. After the project is successfully created, the developer only needs to provide a Docket Bean, as follows:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("org.javaboy.controller"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("Swagger SpringBoot integration")
                        .description("SpringBoot integrate Swagger, details......")
                        .version("9.0")
                        .contact(new Contact("Ahhhhhhh!"."blog.csdn.net"."[email protected]"))
                        .license("The Apache License")
                        .licenseUrl("http://www.javaboy.org") .build()); }}Copy the code

Here we provide a configuration class that first enables Swagger2 with the @enablesWagger2 annotation and then configates a Docket Bean that configates the mapping path and the location of the interface to scan. In the apiInfo, Swagger2 document site information, such as site title, site description, contact information, protocol used, etc.

So, Swagger2 configuration is successful, very convenient.

Start the project at this time, enter http://localhost:8080/swagger-ui.html, can see the following page, that have been configured for success:

Create the interface

Swagger2 interface = Swagger2 interface = Swagger2 interface = Swagger2 interface = Swagger2 interface

@RestController
@Api(tags = "User Management interface")
@RequestMapping("/user")
public class UserController {
    @PostMapping("/")
    @ApiOperation("Add User interface")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "Username", defaultValue = "Bill"),
            @ApiImplicitParam(name = "address", value = "User address", defaultValue = "Shenzhen", required = true)})public RespBean addUser(String username, @RequestParam(required = true) String address) {
        return new RespBean();
    }
    @GetMapping("/")
    @ApiOperation("Interface to query users by ID")
    @ApiImplicitParam(name = "id", value = "User id", defaultValue = "99", required = true)
    public User getUserById(@PathVariable Integer id) {
        User user = new User();
        user.setId(id);
        return user;
    }
    @PutMapping("/{id}")
    @ApiOperation("Update user interface by ID")
    public User updateUserById(@RequestBody User user) {
        returnuser; }}Copy the code

There are several apis involved here, so LET me explain them to you:

  1. The @API annotation can be used to mark the functionality of the current Controller.
  2. The @apiOperation annotation is used to mark what a method does.
  3. The @apiIMPLICITParam annotation is used to describe a parameter. You can configure the Chinese meaning of the parameter or set a default value for the parameter, so that manual input can be avoided during interface testing.
  4. If you have more than one parameter, you need to use multiple @ApiIMPLICITParam annotations to describe it, and multiple @APIIMPLICITParam annotations need to be placed in one @ApiIMPLICITParams annotation.
  5. @requestParam (required = true); @apiIMPLICITParam (required = true); This restriction is useless, so if the developer needs to specify a mandatory parameter, the @requestParam (required = true) annotation should not be omitted.
  6. 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 Integer id;
    @ApiModelProperty(value = "Username")
    private String username;
    @ApiModelProperty(value = "User address")
    private String address;
    //getter/setter
}
Copy the code

Ok, after the configuration above, next, refresh the page just opened, you can see the following:

As you can see, all interfaces are listed here, including the interface request mode, interface address and interface name, etc. Click on an interface, you can see the following information:

Query indicates that the parameter is passed as a key/value. Click Try it Out in the upper right corner to test the interface:

Click the Execute button to send the request for testing. The test results are shown in Response below.

Query (key/value); body (body); body (request body);

There is also a possibility that the parameter is passed in the path, such as query user interface by ID:

Of course, in addition to these, there are some response value annotations, are relatively simple, small partners can explore their own.

Configuration in Security

If Spring Security is integrated into our Spring Boot project, the Swagger2 document may be intercepted if no additional configuration is done, so simply override the configure method in the Spring Security configuration class. Add the following filters:

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

After that, Swagger2 files can be accessed without authentication. I wonder if you can understand it. If you have any questions, please leave a comment. Pay attention to the public account [Jiangnan little Rain], focus on Spring Boot+ micro service and front and back end separation and other full stack technology, regular video tutorial sharing, after attention to reply to Java, get Songko for you carefully prepared Java dry goods!