SpringBoot integration Swagger combat

Source Address: https://github.com/laolunsi/spring-boot-examples

Currently SpringBoot often used to develop Java Web applications, especially before and after the end of the separation project. For the convenience of front and back end developers to communicate, we have introduced Swagger in SpringBoot.

Swagger applied to the interface, the interface allows data visualization, especially for Restful APi

This section describes the two parts, the first part is introduced in two ways SpringBoot Swagger, the second portion of the interface is described in detail in the Web application Swagger annotation.

This article uses SpringBoot 2.1.10.RELEASE and springfox-swagger 2.9.2


A, SpringBoot the introduction of two ways Swagger

Currently SpringBoot There are two ways of using Swagger:

  1. Introducing swagger native dependency springfox-swagger2andspringfox-swagger2-ui
  2. Introduced on domestic Spring4All community developmentswagger-spring-boot-starter

Dependent manner Spring4All taken profile configuration produced, and dependence by native java config class set.

1.1 primeval arrangement Swagger

maven dependence:

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

swagger configuration class:

/**
 * swagger2配置类
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example"))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("基于Swagger构建的Rest API文档")
                .description("更多请咨询服务开发者eknown")
                .contact(new Contact("空夜", "http://www.eknown.cn", "[email protected]"))
                .termsOfServiceUrl("http://www.eknown.com")
                .version("1.0")
                .build();
    }
}

From here you can see a drawback Swagger's: can not be configured by SpringBoot configuration file, so the configuration can not be flexible and change.

spring4all community produced swagger-spring-boot-starter can solve this problem.


1.2 Configuration swagger based spring4all

Spring4All communities Bo main ape DD and a small fire two people developed a Spring Boot Starter Swagger, now line up in the official maven repository.

file

Selecting a first, introduced into the dependency:

<dependency>
    <groupId>com.spring4all</groupId>
    <artifactId>swagger-spring-boot-starter</artifactId>
    <version>1.9.0.RELEASE</version>
</dependency>

Swagger configured in this manner is carried out by application configuration file. One example is given below:

server:
  port: 8106
swagger:
  base-path: /**
  base-package: 'com.example'
  title: 'spring-boot-swagger-demo'
  description: '基于Swagger构建的SpringBoot RESTApi 文档'
  version: '1.0'
  contact:
    name: '空夜'
    url: 'http://www.eknown.cn'
    email: '[email protected]'

Second, the application Swagger build visual interfaces

2.1 Controller class notes add Swagger

The following give a simple example:

@Api(tags = "用户管理")
@RestController
@RequestMapping(value = "user")
public class UserController {

    // 模拟数据库存储的用户
    private static Map<Integer, User> userMap;

    static {
        userMap = new ConcurrentHashMap<>();
        User user = new User(0, "admin", true, new Date());
        userMap.put(user.getId(), user);
    }

    @ApiOperation("列表查询")
    @GetMapping(value = "")
    public List<User> list() {
        return new ArrayList<>(userMap.values());
    }

    @ApiOperation(value = "获取用户详细信息", notes = "路径参数ID")
    @GetMapping(value = "{id}")
    public User detail(@PathVariable Integer id) {
        return userMap.get(id);
    }

    @ApiOperation(value = "新增或更新用户信息", notes = "insert和update共用"
            , response = User.class)
    @PostMapping(value = "")
    public User add(@RequestBody User user) {
        if (user == null || user.getId() == null || !StringUtils.isEmpty(user.getName())
                || userMap.containsKey(user.getId())) {
            return null;
        }

        user.setUpdateTime(new Date());
        userMap.put(user.getId(), user);
        return user;
    }


    @ApiOperation(value = "删除用户")
    @DeleteMapping(value = "{id}")
    public Boolean delete(@ApiParam(name = "用户ID", required = true, example = "100") @PathVariable Integer id) {
        if (userMap.containsKey(id)) {
            userMap.remove(id);
            return true;
        }

        return false;
    }

}

2.2 Parameter entity class notes add Swagger

Entity class may also need to add annotations to determine the parameters of the front-end developer meaning, type, and other examples.

@ApiModel(description = "用户类")
public class User {

    @ApiModelProperty(value = "ID", example = "100")
    private Integer id;

    @ApiModelProperty(value = "姓名", example = "laolunsi")
    private String name;

    @ApiModelProperty(value = "是否启用", example = "1")
    private Boolean enable;

    @ApiModelProperty("更新时间")
    private Date updateTime;

    public User(Integer id, String name, Boolean enable, Date updateTime) {
        this.id = id;
        this.name = name;
        this.enable = enable;
        this.updateTime = updateTime;
    }

    // ... ignore getter and setter methods
}

2.3 Test

Start the project, visit http: // localhost: port / swagger-ui.html

If there server.servlet.context-path configuration, then the access address is http: // localhost: port / context-path / swagger-ui.html

file

In this way, the interface becomes clear, swagger also supports online test interface, similar to the role of postman.


Well, so far, we have successfully integrated Swagger in SpringBoot project, so that the front and rear ends of the development will have a standard butt!

Guess you like

Origin www.cnblogs.com/eknown/p/11834165.html