This is from “Yu Gong Wants to Move mountains”

Included in Springboot Features

This kind of integration of the article has indeed been rotten street, write him on the one hand is to supplement my Springboot series, on the other hand there are indeed some small partners used. Most importantly, if you forget this integration code. You can look it up at any time.

preface

Today’s development is mostly about front – and back-end separation, with front – and back-end interaction through API documentation. With API documentation, everyone develops independently without interfering with each other.

1. The traditional way

Traditionally, the document is designed and sent to the front end and back end respectively. One disadvantage of this is that if the interface information changes, the document needs to be re-sent to the front and back end personnel. You can’t do it in real time. So waste time and energy.

2. swagger

When we integrate Swagger into our backend application, we automatically expose our interface, which is delivered restful. Changes to the back-end interface are immediately visible, thus greatly improving efficiency.

OK, basically one sentence can sum up its benefits, that is, API documents written by the back end can be published in real time in the form of Swagger for the front-end personnel to view.

3. Other ways

Swagger’s page is frankly not good-looking, there are some other solutions, either a lot of bugs, or charges. By far the most used swagger. I am also doing this kind of open source project at present. Based on Swagger, I will make pages similar to other schemes with more powerful functions.

First, code integration

The prerequisite is to create a New SpringBoot project. I’m not going to show you that.

Step 1: Add dependencies

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

Copy the code

Maven 2.9.2 is the most used version. For details, go to the Maven website to find the most used version.

Step 2: Configure

Create a New Config package and create the SwaggerConfig class

@EnableSwagger2

@Configuration

public class Swagger2Config {

    @Bean

    public Docket createRestApi(a) {

        return new Docket(DocumentationType.SWAGGER_2)

             .apiInfo(apiInfo())

             .select()

             // Is the current package path, controller class package

             .apis(RequestHandlerSelectors.basePackage("com.fdd.controller"))

            .paths(PathSelectors.any())

             .build();

    }

    // Build the details function of the API document

    private ApiInfo apiInfo(a) {

        return new ApiInfoBuilder()

            // Page title

           .title(XX Platform API Interface Document)

            / / founder

           .contact(new Contact("Feng Dongdong"."http://www.javachat.cc".

                 "[email protected]"))

           / / version number

          .version("1.0")

           / / description

          .description("System API Description")

          .build();

    }

Copy the code

The configuration here is also relatively simple. There are many options for us to configure. If our project had multiple groups, we would simply create multiple Dockets. In this case, the packets scanned are changed to the packet path of each group.

Step 3: Configure in the Controller class

Create a new Controller package and create the HelloController class

@Api("Hello control class")

@RestController 

public class HelloController {

    @GetMapping(value = "/user")

    public User getUser(a){

        return new User("Yu Gong wanted to move mountains."."123456");

    }

    @ApiOperation("API that can specify parameters")

    @PostMapping("/param")

    public String hello2(@ApiParam("Username") String name){

        return "hello" + name;

    }

}

Copy the code

Here we see that annotations can be used to explain the class, method, field, and so on. There are many other fields, in the use of the time there will be a corresponding prompt, you can try again:


Step 4: Check the effect

Visit: http://127.0.0.1:8080/swagger-ui.html.


Here is the final presentation. OK, that’s pretty much integrated at this point. Here are the configurations you might encounter.

Other common problems

1. Spring Security – Configure authentication-free access

Sometimes Springboot is integrated with SpringSecurity, and visiting Swagger’s address automatically redirects you to the login page. This is because SpringSecurity intercepts it. To do this, we just need to release in our SpringSecurity configuration.


Now configure and release. Create a new SpringSecurityConfig class under the Config package

@Configuration

@EnableWebSecurity

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override

    protected void configure(HttpSecurity http) throws Exception {

        http

                .authorizeRequests()

                .antMatchers("/swagger-ui.html").permitAll()

                .antMatchers("/webjars/**").permitAll()

                .antMatchers("/swagger-resources/**").permitAll()

                .antMatchers("/v2/*").permitAll()

                .antMatchers("/csrf").permitAll()

                .antMatchers("/").permitAll()

                .anyRequest().authenticated()

                .and()

                .formLogin()

        ;

    }

}

Copy the code

At this point, the access is normal.

2. Set JWT for Swagger

This method is relatively simple, only need one step. Just modify our swaggerConfig class.

@EnableSwagger2

@Configuration

public class Swagger2Config {

    @Bean

    public Docket api(a) {

        return new Docket(DocumentationType.SWAGGER_2)

                .apiInfo(apiInfo())

                .securityContexts(Arrays.asList(securityContext()))

                .securitySchemes(Arrays.asList(apiKey()))

                .select()

                .apis(RequestHandlerSelectors.any())

                .paths(PathSelectors.any())

                .build();

    }

    // Build the details function of the API document

    private ApiInfo apiInfo(a) {

        return new ApiInfoBuilder()

                // Page title

                .title(XX Platform API Interface Document)

                / / founder

                .contact(new Contact("Feng Dongdong"."http://www.javachat.cc".

                        "[email protected]"))

                / / version number

                .version("1.0")

                / / description

                .description("System API Description")

                .build();

    }

    private ApiKey apiKey(a) {

        return new ApiKey("JWT"."Authorization"."header");

    }

    private SecurityContext securityContext(a) {

        return SecurityContext.builder().securityReferences(defaultAuth()).build();

    }



    private List<SecurityReference> defaultAuth(a) {

        AuthorizationScope authorizationScope 

         = new AuthorizationScope("global"."accessEverything");

        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];

        authorizationScopes[0] = authorizationScope;

        return Arrays.asList(new SecurityReference("JWT", authorizationScopes));

    }



}

Copy the code

Add some token verification code, relatively simple, about JWT things, you can understand privately. I won’t repeat it here.

3. Hide the Endpoint

Sometimes you write a controller, or interface method in a controller that you don’t want the front end to see, so you can hide it.

First: Hide the entire controller

@ApiIgnore

@RestController

public class MyController {

    / / method

}

Copy the code

Second: Hide an interface method 1

@ApiIgnore

@ApiOperation(value = "Description")

@GetMapping("/getAuthor")

public String getAuthor(a) {

    return "Yu Gong wanted to move mountains.";

}

Copy the code

Third: Hide an interface method 2

@ApiOperation(value = "Description", hidden = true)

@GetMapping("/get")

public LocalDate getDate(a) {

    return LocalDate.now();

}

Copy the code

OK, a lot of the configuration is basically there. This will be supplemented later.