spring-boot integrate with swagger

Add below dependency in pom.xml

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.16.8</version>
</dependency>

Add the @EnableSwagger2 annotation to the Application class

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

Key annotations of swagger

Annotation Comments
@ApiModel Model name like ‘User Model’
@ApiModelProperty The property description like ‘Name’, ‘Password’
@Api The API description like ‘User API’
@ApiOperation The API method description like ‘Get User By Id’
@ApiImplicitParams Will contains list of @ApiImplicitParam
@ApiImplicitParam the parameter definition
@ApiResponses Contains list of @ApiResponse
@ApiResponse the response definition

Sample for domain POJO

@ApiModel("User Model")
@AllArgsConstrcutor
@Getter
public class User {
    @ApiModelProperty("User ID")
    private int id;
    @ApiModelProperty("User Name")
    private String name;
    @ApiModelProperty("Password")
    private String password;
}

Note below annotations comes from lombok dependency
(Need IDE support lombok plugin)

Annotation Comments
@AllArgsConstrcutor It will automatically generate the constructor
@NoArgsConstrcutor It will automatically generate the constructor with empty parameters
@Getter It will automatically generate the getterXX() method
@Setter It will automatically generate the setXX() method
@Builder convert the class to builder strategy
@Data Contains @NoArgsConstrcutor @Setter @Getter and will override toString(),hashcode(),equals() methods

Sample for controller

@Api("User API")
@RestController
@RequestMapping("/user")
public class UserControll {
    @ApiOperation("Get the user by id")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="path",name="id",dataType="int",required=true,value="User ID",defaultValue="0")
    })
    @ApiResponses({
        @ApiResponse(code=403, message="Access forbidden"),
        @ApiResponse(code=404, message="Page not found")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable("id") int id) {
        return new User();
    }
}

Reference

《Java微服务实战》- 赵计刚

猜你喜欢

转载自blog.csdn.net/javalover_yao/article/details/82222136