SpringBoot integrates Swagger2

1. Dependence

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

Two, Swagger configuration class

For this configuration class, as long as you know what specific things can be configured, after all, you don’t need to move this thing after you configure it once. Special attention should be paid to the configuration of the api file, which is the path of the controller package, otherwise the generated document cannot scan the interface

package cn.saytime;
 
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
 
/**
 * @author zh
 * @ClassName cn.saytime.Swgger2
 * @Description
 * @date 2017-07-10 22:12:31
 */
@Configuration
public class Swagger2 {
 
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType. SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.saytime.web"))
                .paths(PathSelectors. any())
                .build();
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot uses swagger to build api documentation")
                .description("Simple and elegant restfun style, http://blog.csdn.net/saytime")
                .termsOfServiceUrl("http://blog.csdn.net/saytime")
                .version("1.0")
                .build();
    }
}

Annotating this class with @Configuration is equivalent to configuring beans in XML; annotating methods with @Bean is equivalent to configuring beans in XML.

Application.class plus annotation @EnableSwagger2 means to enable Swagger

package cn.saytime;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
@SpringBootApplication
@EnableSwagger2
public class SpringbootSwagger2Application {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringbootSwagger2Application.class, args);
    }
}

3. Restful interface

package cn.saytime.web;
 
import cn.saytime.bean.JsonResult;
import cn.saytime.bean.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * @author zh
 * @ClassName cn.saytime.web.UserController
 * @Description
 */
@RestController
public class UserController {
 
    // Create a thread-safe Map
    static Map<Integer, User> users = Collections. synchronizedMap(new HashMap<Integer, User>());
 
    /**
     * Query user by ID
     * @param id
     * @return
     */
    @ApiOperation(value="Get user details", notes="Get user details according to the id of the url")
    @ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "Integer", paramType = "path")
    @RequestMapping(value = "user/{id}", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id){
        JsonResult r = new JsonResult();
        try {
            User user = users. get(id);
            r. setResult(user);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
 
    /**
     * Query user list
     * @return
     */
    @ApiOperation(value="Get user list", notes="Get user list")
    @RequestMapping(value = "users", method = RequestMethod. GET)
    public ResponseEntity<JsonResult> getUserList (){
        JsonResult r = new JsonResult();
        try {
            List<User> userList = new ArrayList<User>(users. values());
            r. setResult(userList);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
 
    /**
     * Add user
     * @param user
     * @return
     */
    @ApiOperation(value="Create user", notes="Create user based on User object")
    @ApiImplicitParam(name = "user", value = "user detailed entity user", required = true, dataType = "User")
    @RequestMapping(value = "user", method = RequestMethod. POST)
    public ResponseEntity<JsonResult> add (@RequestBody User user){
        JsonResult r = new JsonResult();
        try {
            users. put(user. getId(), user);
            r.setResult(user.getId());
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
 
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
 
    /**
     * Delete user by id
     * @param id
     * @return
     */
    @ApiOperation(value="Delete user", notes="Delete user according to the id of url")
    @ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "Long", paramType = "path")
    @RequestMapping(value = "user/{id}", method = RequestMethod. DELETE)
    public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") Integer id){
        JsonResult r = new JsonResult();
        try {
            users. remove(id);
            r. setResult(id);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
 
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
 
    /**
     * Modify user information according to id
     * @param user
     * @return
     */
    @ApiOperation(value="Update information", notes="Specify update user information according to url id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "Long",paramType = "path"),
            @ApiImplicitParam(name = "user", value = "user entity user", required = true, dataType = "User")
    })
    @RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
    public ResponseEntity<JsonResult> update (@PathVariable("id") Integer id, @RequestBody User user){
        JsonResult r = new JsonResult();
        try {
            User u = users. get(id);
            u.setUsername(user.getUsername());
            u.setAge(user.getAge());
            users. put(id, u);
            r. setResult(u);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
 
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
 
    @ApiIgnore//Use this annotation to ignore this API
    @RequestMapping(value = "/hi", method = RequestMethod. GET)
    public String jsonTest() {
        return "hi you!";
    }
}

Json format output class JsonResult.class

package cn.saytime.bean;
 
public class JsonResult {
 
    private String status = null;
 
    private Object result = null;
 
    // Getter Setter
}

EntityUser.class

package cn.saytime.bean;
 
import java.util.Date;
 
/**
 * @author zh
 * @ClassName cn.saytime.bean.User
 * @Description
 */
public class User {
 
    private int id;
    private String username;
    private int age;
    private Date ctm;
 
    // Getter Setter
}

Project structure: