1. 程式人生 > >Spring boot 使用Swagger2構建RESTful API文件

Spring boot 使用Swagger2構建RESTful API文件

前言

SwaggerUI可以說是一個非常好用的API文件工具,是前後端分離開發模式下的必備工具、具體實現及部分乾貨知識如下

匯入依賴
<!-- RESTful APIs swagger2 -->
<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>
編寫配置類
/**
 * swagger-ui的配置
 * api頁面 /swagger-ui.html
 * 如controller在不同的包中,@ComponentScan(basePackages = {"*","..."})
 * @author 鄭傑
 * @date 2018/10/28 12:44:04
 */

@Configuration
@EnableSwagger2
@ComponentScan(basePackages = {"me.zhengjie.controller"})
public class Swagger2Config {

    @Bean
    public Docket createRestApi
() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .paths(Predicates.not(PathSelectors.regex("/error.*"))) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .
title("RESTful API") .termsOfServiceUrl("https://gitee.com/hgpt/SpringBoot_All") .description("Spring Boot 使用Swagger2構建RESTful APIs") .version("1.0") .build(); } }

編寫實體及控制器

User.class

@Entity
@Table(name = "user")
@Data
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;

    private Integer age;

    private String sex;
}

UserController.class

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserRepo userRepo;

    @GetMapping
    public ResponseEntity findAll(@PageableDefault(value = 10, sort = {"id"}) Pageable pageable){
        return ResponseEntity.ok(userRepo.findAll(pageable));
    }

    @PostMapping
    public ResponseEntity save(@RequestBody User user){
        userRepo.save(user);
        return new ResponseEntity(HttpStatus.CREATED);
    }

    @PutMapping
    public ResponseEntity update(@RequestBody User user){
        userRepo.save(user);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping(value = "/{id}")
    public ResponseEntity del(@PathVariable Long id){
        userRepo.deleteById(id);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

}
啟動專案檢視

swagger預設啟動地址: 專案地址後面加/swagger-ui.html 如:http://localhost:8080/swagger-ui.html#

檢視效果

擴充套件知識

擴充套件支援Token傳入

修改Swagger2Config中的createRestApi方法

@Bean
    public Docket createRestApi() {
        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        ticketPar.name("Authorization").description("token")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .defaultValue("Bearer ")
                .required(true)
                .build();
        pars.add(ticketPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build()
                .globalOperationParameters(pars);
    }

檢視效果

@ApiModelProperty

此註解加入在實體類中的欄位上,如:


    @ApiModelProperty(hidden = true)
    private Long id;

我們新增時ID是自增的,所以就不需要顯示ID,這個時候不隱藏掉可能會誤導前端人員呼叫,通過此註解可以在User的資料結構中隱藏ID屬性 效果如下:

@ApiOperation

該註解是加在方法上面的,用於給API增加說明

@ApiOperation(value="建立使用者", notes="根據User物件建立使用者")
    @PostMapping
    public ResponseEntity save(@RequestBody User user){
        userRepo.save(user);
        return new ResponseEntity(HttpStatus.CREATED);
    }

效果如下:

@ApiImplicitParam

該註解是給介面的屬性新增描述

@ApiOperation(value="刪除使用者", notes="根據UserId刪除使用者")
    @ApiImplicitParam(name = "id", value = "使用者ID", required = true, dataType = "Long")
    @DeleteMapping(value = "/{id}")
    public ResponseEntity del(@PathVariable Long id){
        userRepo.deleteById(id);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

效果如下:

如果有多個屬性,可以使用

@ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "使用者ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "age", value = "使用者年齡", required = true, dataType = "Integer")
    })

參考資訊

專案原始碼

開源後臺管理系統:

歡迎體驗Aurora