[Swagger2] SpringBoot integrates springfox-swagger2 to build restful API

springboot integrates swagger2

The article  SpringMVC integrated springfox-swagger2 to build restful API  simply wrote how to integrate swagger2 in springmvc. Here is how to integrate swagger2 in springboot. In fact, the usage is basically the same.

1. Introduce dependencies

Using maven, reference related dependencies in pom.xml (swagger version 2.4.0, springboot version 2.1.5.RELEASE):

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

Second, create a configuration class for swagger

This configuration class is exactly the same as that of springmvc.

package com.xingguo.springboot;

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

@Configuration
@EnableSwagger2
public class Swagger2Configuration {

    @Bean
    public Docket buildDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(buildApiInf())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xingguo.springboot.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo buildApiInf(){
        return new ApiInfoBuilder()
                    .title("xingguo大标题")
                    .description("springboot swagger2")
                    .termsOfServiceUrl("http://blog.csdn.net/u014231523网址链接")
                    .contact(new Contact("diaoxingguo", "http://blog.csdn.net/u014231523", "[email protected]"))
                    .build();

    }

}

Among them, in addition to RequestHandlerSelectors.basePackage (xxx) need to be modified, other configurations do not need to be changed.

In the original version 2.2.0, the method of using new ApiInfo() is outdated. Use new ApiInfoBuilder() to construct, and add whatever parameters are needed. Of course you can add everything. Such as:

private ApiInfo buildApiInfo(){
    return new ApiInfoBuilder().build();
}

Three, add relevant annotations in the controller

Commonly used annotations are as follows:
-@Api() for class name-
@ApiOperation() for method name-
@ApiParam() for parameter description-
@ApiModel() for entity class-
@ApiModelProperty for entity class attribute

For more detailed meaning, please refer to the  official description wiki  , which will be explained with code and sample pictures below.

Fourth, start the project

Enter the url on the browser: http://{ip}:{port}/swagger-ui.html#/, there is no need to enter #/ in the url

Set the port number in application.properties to 9090 (if not set, the default is 8080)

server.port=9090

So the url is: http://localhost:9090/swagger-ui.html , as shown in the figure:
Write picture description here
Here, all controllers under the corresponding package will be displayed by category (tag or @Api).

Five, sample code

Let's look at one of the classes UserController.java, ( please ignore the business logic, just look at the comments )

package com.xingguo.springboot.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.xingguo.springboot.model.User;
import com.xingguo.springboot.service.UserService;


@Api(value="用户controller",description="用户操作",tags={"用户操作接口"})
@RestController
public class UserController {

    @Resource
    private UserService userService;

    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    public User getUserInfo(@ApiParam(name="id",value="用户id",required=true) Long id,@ApiParam(name="username",value="用户名") String username) {
        User user = userService.getUserInfo();
        return user;
    }

    @ApiOperation("更改用户信息")
    @PostMapping("/updateUserInfo")
    public int updateUserInfo(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user){
        int num = userService.updateUserInfo(user);
        return num;
    }

    @ApiOperation("添加用户信息")
    @PostMapping("/saveUser")
    public String saveUser(@RequestBody @ApiParam(name="user",value="json fromat",required=true) User user) {
        userService.saveUser(user);
        return "success";
    }
}

It is explained here that when using an object as a parameter, you can add corresponding annotations to the object, and the user page will be displayed. Such as:

package com.xingguo.springboot.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.List;

@ApiModel(description="用户对象user")
public class User {
    @ApiModelProperty(value="用户名",name="username")
    private String username;
    @ApiModelProperty(value="状态",name="state",required=true)
    private Integer state;
    private String password;
    private String nickName;
    private Integer isDeleted;

    private String[] ids;
    private List<String> idList;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String[] getIds() {
        return ids;
    }

    public void setIds(String[] ids) {
        this.ids = ids;
    }

    public List<String> getIdList() {
        return idList;
    }

    public void setIdList(List<String> idList) {
        this.idList = idList;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public Integer getIsDeleted() {
        return isDeleted;
    }

    public void setIsDeleted(Integer isDeleted) {
        this.isDeleted = isDeleted;
    }

}

The displayed effect is as follows:
Write picture description here
Write picture description here
look at the red box in the figure above, one of which is in json format, click to get the parameter format.

In the second sheet, you can see the corresponding comments of the fields and whether they are required. If you add the annotation @ApiModelProperty(required=true) to the field, it is required (the default is false), the optional logo on the corresponding page will also disappear, and this field is required.

You can debug by clicking the try it out button below.

When using a single parameter, such as the getUserInfo() method in the above code, the corresponding effect diagram is as follows:
Write picture description here
if required=true is added here, @ApiParam(required=true) will display the required logo on the page. The same default is false. You can try other ways of using it yourself.

Reference article

https://blog.csdn.net/u014231523/article/details/54562695

Guess you like

Origin blog.csdn.net/xiaoxiao_su123/article/details/112872986