Source code address: github.com/laolunsi/sp…

Currently SpringBoot is often used to develop Java Web applications, especially for back-end separation projects. To facilitate communication between front-end and back-end developers, we have introduced Swagger in SpringBoot.

Swagger works on interfaces to visualize interface data, especially for Restful apis

This section is divided into two parts. The first part is the two ways SpringBoot introduces Swagger, and the second part is the annotation of applying Swagger on the Web interface.

This article uses SpringBoot 2.1.10.release and Springfox-Swagger 2.9.2


SpringBoot introduces Swagger in two ways

Currently SpringBoot has two ways to use Swagger:

  1. Introduce swagger native dependenciesspringfox-swagger2andspringfox-swagger2-ui
  2. The introduction of domestic Spring4All community development dependencyswagger-spring-boot-starter

Spring4All’s dependencies are configured as configuration files, whereas native dependencies are set up through Java Config classes.

1.1 Native Configuration Swagger

Maven depends on:

<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

Swagger configuration class:

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


    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                .title("Rest API Documentation built on Swagger")
                .description("For more information please consult service developer Eknown.")
                .contact(new Contact("Empty night"."http://www.eknown.cn"."[email protected]"))
                .termsOfServiceUrl("http://www.eknown.com")
                .version("1.0") .build(); }}Copy the code

One disadvantage of Swagger is that it cannot be configured through SpringBoot configuration files, so configuration is not flexible.

Spring4all’s Swagger-Spring-boot-Starter solves this problem.


1.2 Configuring Swagger Based on Spring4All

Spring Boot Starter Swagger has been developed by DD and Xiao Fire, the bloggers of Spring4All, and is now available in maven’s official repository.

Select the first and introduce the dependency:

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

Swagger configuration in this manner is done through the Application configuration file. Here is an example:

server:
  port: 8106
swagger:
  base-path: / * *
  base-package: 'com.example'
  title: 'spring-boot-swagger-demo'
  description: 'SpringBoot RESTApi document built on Swagger'
  version: '1.0'
  contact:
    name: 'empty night'
    url: 'http://www.eknown.cn'
    email: '[email protected]'
Copy the code

2. Apply Swagger to build interface visualization

2.1 Add Swagger annotation to Controller class

Here is a simple example:

@Api(tags = "User Management")
@RestController
@RequestMapping(value = "user")
public class UserController {

    // Simulate the user of database storage
    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("List query")
    @GetMapping(value = "")
    public List<User> list(a) {
        return new ArrayList<>(userMap.values());
    }

    @ApiOperation(value = "Get user details", notes = "Path parameter ID")
    @GetMapping(value = "{id}")
    public User detail(@PathVariable Integer id) {
        return userMap.get(id);
    }

    @ApiOperation(value = "Add or update user information", notes = "Insert and update shared"
            , 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 = "Delete user")
    @DeleteMapping(value = "{id}")
    public Boolean delete(@ApiParam(name = "User ID", required = true, example = "100") @PathVariable Integer id) {
        if (userMap.containsKey(id)) {
            userMap.remove(id);
            return true;
        }

        return false; }}Copy the code

2.2 Parameter entity Class add Swagger annotation

The entity classes also need to be annotated so that the front-end developer can determine the meaning, types, examples, and so on of the parameters.

@ApiModel(description = "User class")
public class User {

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

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

    @ApiModelProperty(value = "Enabled or not", example = "1")
    private Boolean enable;

    @ApiModelProperty("Update Time")
    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
}

Copy the code

2.3 test

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

If there is a server. The servlet. The context – path configuration, then visit http://localhost:port/context-path/swagger-ui.html

Swagger also supports an online testing interface, similar to postman.


Ok, so far we have successfully integrated Swagger in the SpringBoot project so that the front and back end development docking is standard!


learn

My personal website: www.eknown.cn

Git repository address: github.com/laolunsi

Also welcome to my public attention number: apes language, learn Java/SpringBoot/SpringCloud technology together.