SpringBoot 2.0 integrates Swagger 2 and builds interface management interface

Keywords: Java Spring github SpringBoot

Introduction to Swagger 2

1. Swagger 2 Advantages

Integrate into Spring Boot to build powerful RESTful API documents. Swagger2 also provides powerful page testing capabilities to debug RESTful API without interface document management, code modification and automatic updates.

2. Swagger 2 Common Notes

Api: Modify the entire class to describe the role of Controller
 ApiOperation: A method, or interface, that describes a class
 ApiParam: Single parameter description
 ApiModel: Receiving parameters with objects
 ApiProperty: A field describing an object when it receives parameters with an object
 ApiResponse: One description of HTTP response
 ApiResponses: Overall description of HTTP response
 ApiIgnore: Use this annotation to ignore the API
 ApiError: Information returned when an error occurred
 ApiImplicitParam: A request parameter
 ApiImplicitParams: Multiple request parameters

Integration with SpringBoot 2.0

1. Core Dependence

spring-boot: 2.1.3.RELEASE
swagger: 2.6.1

2. Swagger 2 configuration

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;
/**
 * Swagger configuration file
 */
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.swagger.two"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot utilize Swagger structure API File")
                .description("Use RestFul style, Founder: Know a smile")
                .termsOfServiceUrl("https://github.com/cicadasmile")
                .version("version 1.0")
                .build();
    }
}

3. Adding annotations to startup classes

@EnableSwagger2
@SpringBootApplication
public class SwaggerApplication {
    public static void main(String[] args) {
        SpringApplication.run(SwaggerApplication.class,args) ;
    }
}

4. Start-up effect map

3. Cases of Addition, Deletion, Amendment and Examination

1. Adding Users

(1) Code block

@ApiOperation(value="Add user", notes="Create new users")
@ApiImplicitParam(name = "user", value = "User Detailed Entities user", required = true, dataType = "User")
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public ResponseEntity<JsonResult> addUser (@RequestBody User user){
    JsonResult result = new JsonResult();
    try {
        users.put(user.getId(), user);
        result.setResult(user.getId());
        result.setStatus("ok");
    } catch (Exception e) {
        result.setResult("Service exception");
        result.setStatus("500");
        e.printStackTrace();
    }
    return ResponseEntity.ok(result);
}

(2) Effect map

2. User List

(1) Code block

@ApiOperation(value="User list", notes="Query User List")
@RequestMapping(value = "/getUserList", method = RequestMethod.GET)
public ResponseEntity<JsonResult> getUserList (){
    JsonResult result = new JsonResult();
    try {
        List<User> userList = new ArrayList<>(users.values());
        result.setResult(userList);
        result.setStatus("200");
    } catch (Exception e) {
        result.setResult("Service exception");
        result.setStatus("500");
        e.printStackTrace();
    }
    return ResponseEntity.ok(result);
}

(2) Effect map

3. User Query

(1) Code block

@ApiOperation(value="User query", notes="according to ID Query users")
@ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "Integer", paramType = "path")
@RequestMapping(value = "/getUserById/{id}", method = RequestMethod.GET)
public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id){
    JsonResult result = new JsonResult();
    try {
        User user = users.get(id);
        result.setResult(user);
        result.setStatus("200");
    } catch (Exception e) {
        result.setResult("Service exception");
        result.setStatus("500");
        e.printStackTrace();
    }
    return ResponseEntity.ok(result);
}

(2) Effect map

4. Update Users

(1) Code block

@ApiOperation(value="Update user", notes="according to Id Update user information")
@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "Long",paramType = "path"),
        @ApiImplicitParam(name = "user", value = "User object user", required = true, dataType = "User")
})
@RequestMapping(value = "/updateById/{id}", method = RequestMethod.PUT)
public ResponseEntity<JsonResult> updateById (@PathVariable("id") Integer id, @RequestBody User user){
    JsonResult result = new JsonResult();
    try {
        User user1 = users.get(id);
        user1.setUsername(user.getUsername());
        user1.setAge(user.getAge());
        users.put(id, user1);
        result.setResult(user1);
        result.setStatus("ok");
    } catch (Exception e) {
        result.setResult("Service exception");
        result.setStatus("500");
        e.printStackTrace();
    }
    return ResponseEntity.ok(result);
}

(2) Effect map

5. Delete Users

(1) Code block

@ApiOperation(value="delete user", notes="according to id Delete the specified user")
@ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "Long", paramType = "path")
@RequestMapping(value = "/deleteById/{id}", method = RequestMethod.DELETE)
public ResponseEntity<JsonResult> deleteById (@PathVariable(value = "id") Integer id){
    JsonResult result = new JsonResult();
    try {
        users.remove(id);
        result.setResult(id);
        result.setStatus("ok");
    } catch (Exception e) {
        result.setResult("Service exception");
        result.setStatus("500");
        e.printStackTrace();
    }
    return ResponseEntity.ok(result);
}

(2) Effect map

Source Code

GitHub Address: Know a smile
https://github.com/cicadasmile/middle-ware-parent
 Code Yun Address: Know a smile
https://gitee.com/cicadasmile/middle-ware-parent

Posted by SoundreameR on Fri, 04 Oct 2019 22:40:59 -0700