I heard that wechat search “Java fish” will change strong!

This article is in Java Server, which contains my complete series of Java articles, can be read for study or interview

(1) Introduction

In my first job, I used an older technology architecture, and I wrote an interface document manually when WRITING Api interfaces. But once there are more interfaces, these documents become difficult to manage. My current work uses SpringBoot at the application level and Swagger2 is used extensively in projects. I personally feel that Swagger’s strength is that with very little configuration and a few comments it can produce a complete technical document that integrates maintenance documentation and code modification, saving a lot of time.

(2) Swagger and SpringBoot integration

Swagger is easy to use and is illustrated here with a simple example

(2.1) Introducing dependencies

We need to create a Springboot project and introduce Swagger2 dependencies:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.92.</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.92.</version>
</dependency>
Copy the code

(2.2) Create an entity class

Because the project is relatively simple, it realizes the API interface of adding, deleting, modifying and checking User class, so it is put in a folder to create User.java. Here we use swagger’s two annotations @apiModel and @apiModelProperty for the entity class. Represents the meaning of the entity class and the meaning of the attribute respectively.

@Data
@apiModel (" User entity class ")
public class User {
    @ApiModelProperty("id")
    private Long id;
    @ApiModelProperty("name")
    private String name;
    @ApiModelProperty("age")
    private Integer age;
}
Copy the code

(2.3) Create Swagger2 profile

Swagger Configuration includes basic display and scan information. The @Configuration annotation enables Spring to start this Configuration class and @enablesWagger2 to start Swagger2

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(a){
        return new Docket(DocumentationType.SWAGGER_2)
                // Create basic API information
                .apiInfo(apiInfo())
                .select()
                / / RequestHandlerSelectors basePackage scan packages specified path
                / / RequestHandlerSelectors. Any () : scan all of them
                / / RequestHandlerSelectors. None () : do not scan
                / / RequestHandlerSelectors withClassAnnotation () : scans the annotation on the class
                / / RequestHandlerSelectors withMethodAnnotation () : the annotations on scanning method
                .apis(RequestHandlerSelectors.basePackage("com.javayz.swaggerdemo.controller"))
                // Filter what path
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                .title("SwaggerAPI file for Java fish")
                .description("You get tired because you're walking uphill.")
                .termsOfServiceUrl("https://blog.csdn.net/qq_41973594")
                .contact(new Contact("Java fish larvae"."https://blog.csdn.net/qq_41973594"."[email protected]"))
                .version("1.0") .build(); }}Copy the code

The parameters in ApiInfo are as follows:

(2.4) Create Controller and define API

@api (value = "user info management ")
@RestController
@RequestMapping(value="/users")
public class UserController {

    Create a thread-safe map
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());

    // Get the User list
    @apiOperation (value=" get user list ", notes="")
    @RequestMapping(value={""}, method= RequestMethod.GET)
    public List<User> getUserList(a) {
        List<User> r = new ArrayList<User>(users.values());
        return r;
    }
    // Delete users based on the user ID
    @apiOperation (value = "delete user by id ",notes =" delete user by ID ")
    @APIIMPLICITParam (name = "id",value = "Enter user ID ", Required = true,dataType = "Long") @APIIMPLICITParam (name = "id",value =" Enter user ID ", Required = true,dataType = "Long")
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public String DeleteList(@PathVariable Long id){
        users.remove(id);
        return "success";
    }
    // Create a user
    @apiOperation (value=" create User ", notes=" create User from User object ")
    @APIIMPLICITParam (name = "user", value = "user detail entity user", Required = true, dataType = "user")
    @RequestMapping(value="", method=RequestMethod.POST)
    public String postUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }
    // Obtain user information based on the user ID
    @apiOperation (value=" get user details ", notes=" get user details based on URL ID ")
    @APIIMPLICITParam (name = "id", value = "user ID", Required = true, dataType = "Long")
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }
    // Updates the object with the specified ID
    @apiOperation (value=" update user details ", notes=" specify update object based on URL ID and update user details based on passed user information ")
    @APIIMPLICITParams ({@APIIMPLICITParam (name = "id", value = "user ID", Required = true, dataType = "Long"), @APIIMPLICITParam (name = "user", value = "user detail entity user", Required = true, dataType = "user")})
    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @RequestBody User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success"; }}Copy the code

At first glance, the above code looks like a lot of configuration files, but it’s actually very simple to use. Add instructions to the Api via @API and @ApiOperation annotations, and add instructions to parameters via @APIIMPLicitParams and @ApiIMPLicitParam annotations. The function of annotating each parameter is as follows:

@Api: used on the requested class to indicate a description of the class tags="Notes that illustrate the purpose of this class that can be seen on the UI."
    value="This parameter is meaningless, it is also seen in the UI, so it does not need to be configured."
 
@ApiOperationValue = : specifies the purpose of the method used in the request"Explain the purpose and function of the method"
    notes="Method remarks"
 
@ApiImplicitParams: used in the request method to represent a set of parameter descriptions@ApiImplicitParam: in the@ApiImplicitParamsName: parameter name value: Chinese characters for parameters required: Whether the parameter must be passed paramType: where to put the parameter · Header --> Get the request parameter:@RequestHeader· Query --> Request parameter fetch:@RequestParam· Path (used for restful interfaces) --> Obtain request parameters:@PathVariable· Body (not common) · Form (not common) dataType: Parameter type, default String, other values dataType="Integer"DefaultValue: indicates the defaultValue of the parameter@ApiResponses: Used in the form of a request to represent a set of responses@ApiResponse: in the@ApiResponsesIn, generally used to express an error response message code: a number, e.g400Message: a message, for example"Request parameters are not filled in."Response: Class that throws an exception@ApiModel: used on a response class to represent a message that returns response data. (This is typically used when a POST is created@RequestBodyIn such a scenario, the request parameters are not available@ApiImplicitParamNotes to describe)@ApiModelProperty: applies to properties that describe the properties of the response classCopy the code

(3) Operation of projects

Complete code, start SpringBoot project, enter http://localhost:8080/swagger-ui.html in the browser, you can see a RESTful API interfaces

This interface allows you to test the interface directly, and every code change is synchronized to the interface documentation. We just need to send this path to the front end and we’re done.

(4) Summary

The purpose of the framework is to simplify our development, and the proper use of the framework can double our efficiency. I’m fish boy, and I’ll see you next time.