SpringBoot integrates Swagger2, and sets springsecurity release and token

Original: http://springboot.javaboy.org/2019/0416/springboot-swagger

After the front and back ends are separated, maintaining interface documents is basically an indispensable work. An ideal state is that after the design is completed, the interface documents are sent to the front-end and the back-end, and everyone develops them separately according to the established rules. After the development is completed, it can be launched online. Of course, this is a very ideal state. In actual development, such a situation is rarely encountered. The interface is always in constant change. If there is a change, it must be maintained. All the friends who have done it know this. What a big head! Fortunately, there are some tools that can reduce our workload. Swagger2 is one of them. As for other software with similar functions but with a fee, I won't introduce too much here. This article mainly talks with everyone about how to integrate Swagger2 in Spring Boot.

Project creation

Of course, the first step is to create a Spring Boot project and add web dependencies. After the creation is successful, add two Swagger2 related dependencies. The complete dependencies are 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

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

.apis(RequestHandlerSelectors.basePackage(" com.nvn.controller ")) Fill in your own package.

ticketPar.name(" Authorization ").description(" Bearer ") Set according to your own token

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        ticketPar.name("Authorization").description("Bearer ")//Token 以及Authorization 为自定义的参数,session保存的名字是哪个就可以写成那个
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build(); //header中的ticket参数非必填,传空也可以
        pars.add(ticketPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.nvn.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.baidu.com")
                        .build()).globalOperationParameters(pars);
    }
}

Here is a configuration class. 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, you mainly configure the information of the Swagger2 document website, such as the website The title, the description of the website, the contact information, the protocol used, etc.

In this way, even if Swagger2 is successfully configured, it is very convenient.

Start the project at this time, enter http://localhost:8080/swagger-ui.html, you can see the following page, indicating that the configuration has been successful:

Create interface

The next step is to create the interface. There are not many annotations related to Swagger2, and it is easy to understand. Let me illustrate to the friends:

@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
public class UserController {

    @PostMapping("/")
    @ApiOperation("添加用户的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", defaultValue = "李四"),
            @ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "深圳", required = true)
    }
    )
    public RespBean addUser(String username, @RequestParam(required = true) String address) {
        return new RespBean();
    }

    @GetMapping("/")
    @ApiOperation("根据id查询用户的接口")
    @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99", required = true)
    public User getUserById(@PathVariable Integer id) {
        User user = new User();
        user.setId(id);
        return user;
    }
    @PutMapping("/{id}")
    @ApiOperation("根据id更新用户的接口")
    public User updateUserById(@RequestBody User user) {
        return user;
    }
}

There are multiple APIs involved here, let me explain to my friends:

  1. The @Api annotation can be used to mark the function of the current Controller.
  2. The @ApiOperation annotation is used to mark the role of a method.
  3. The @ApiImplicitParam annotation is used to describe a parameter. You can configure the Chinese meaning of the parameter, or set the default value for the parameter, so that manual input can be avoided during interface testing.
  4. If there are multiple parameters, you need to use multiple @ApiImplicitParam annotations to describe, and multiple @ApiImplicitParam annotations need to be placed in one @ApiImplicitParams annotation.
  5. It should be noted that although the @ApiImplicitParam annotation can specify that the parameter is required, it cannot replace @RequestParam(required = true). The former is required only in the framework of Swagger2. Abandoning Swagger2, this restriction does not apply. Used, so if the developer needs to specify a required parameter, the @RequestParam(required = true) annotation still cannot 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 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, next, refresh the page just opened, you can see the following effects:

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

As you can see, the interface parameters, parameter requirements, parameter default values, etc. are all displayed. The query under the parameter type indicates that the parameters are passed in the form of key/value. Click Try it out in the upper right corner to perform interface testing. :

Click the Execute button to send a request for testing. The test results will be displayed in the Response below.

Please note that the query below the parameter type indicates that the parameter is passed in the form of key/value. The value here may also be body, and body indicates that the parameter is passed in the form of the request body. For example, the update interface above is as follows:

Of course, there is another possibility that the parameter here is path, which means that the parameter is passed in the path, such as querying the user's interface based on id:

Of course, in addition to these, there are some comments on the response value, which are relatively simple, and friends can explore it by themselves.

Configuration in Security

If Spring Security is integrated in our Spring Boot project, then if no additional configuration is made, the Swagger2 document may be intercepted. At this time, you only need to rewrite the configure method in the Spring Security configuration class and add the following filtering:

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

After this, Swagger2 files can be accessed without authentication. I don’t know if my friends understand it? If you have any questions, please leave a message to discuss

Fill in the token location

 

 

If it returns nginx 404 when deployed to the server, it means that the html suffix link was intercepted by nginx to other paths, and it was not found.

You can try to use ip+port access.

Guess you like

Origin blog.csdn.net/qq_29752857/article/details/113390619