Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

background

Recently I am learning SpringBoot, so I will integrate some components by myself. This time we will integrate Swagger2 to realize the online documentation of API.

The effect is as shown below:

Let’s take a look at the integrated Swagger2 components from 0 to 1.

The specific deployment of the implementation

First introduce the JAR package component, edit the POM file, and add the following code:

Note: The creation of the SpringBoot project is not described here, please solve it yourself.

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
Copy the code

After that, we’ll write an auto-configuration class that looks like this:

@Configuration
@EnableSwagger2
public class Swagger2Configuration {

    @Value(value = "${swagger.enable}")
    private boolean swaggerEnable;

    @Bean
    public Docket createRestApi(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(swaggerEnable)
                .select()
                .apis(RequestHandlerSelectors.any())
                // Error paths are not monitored
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                // Monitor all paths under the root
                .paths(PathSelectors.regex("/. *"))
                .build();
    }

    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                .title("API")
                .description("The project provides all external API, please check.")
                .termsOfServiceUrl("http://www.test.com")
                .version("1.0") .build(); }}Copy the code

After the preparation of the configuration class, in fact, almost completed this preparation.

However, there is one thing that has not been done is to configure the parameter swaggerEnable in the class. We have not configured this parameter so far, so we need to add this parameter in application.yml.

Add the following code to the configuration file:

swagger:
  enable: true
Copy the code

After adding this configuration, the page can be accessed normally with the corresponding page address localhost:8080/swagger-ui.html, so that you can get the effect of the beginning of the article.