springboot-swagger:配置實體類和注釋


承接:springboot-swagger:配置API分組

1 配置實體類

1.1 創建pojo包,並在該包下編寫用戶實體類

src/main/java/com/lv/pojo/User.java

package com.lv.pojo;

public class User {
    public String username;
    public String password;
}

1.2 編寫HelloControlelr

在控制類中編寫一個請求,只要這個實體在請求的返回值上(即使是泛型),都能映射到實體項中

src/main/java/com/lv/controller/HelloController.java

package com.lv.controller;

import com.lv.pojo.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

    //只要我們的接口中,返回值中存在實體類,他就會被掃描到Swagger中
    @PostMapping(value = "/user")
    public User user(){
        return new User();
    }
}

1.3 啟動程序測試

實體類顯示成功

2 swagger中的注釋

swagger的注釋都是通過添加注解的方式實現

2.1給用戶類添加注釋的注解

@ApiModel為類添加注釋

@ApiModelProperty為類屬性添加注釋

src/main/java/com/lv/pojo/User.java

package com.lv.pojo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

//@Api(注釋)
@ApiModel("用戶實體類")
public class User {
    @ApiModelProperty("用戶名")
    public String username;
    @ApiModelProperty("密碼")
    public String password;
}

2.2 啟動程序查看注釋位置

2.3 給請求接口配置注釋的注解

@ApiOperation 為接口方法添加注釋

@ApiParam 為參數添加注釋

src/main/java/com/lv/controller/HelloController.java

@ApiOperation("hello控制類")
@GetMapping(value = "/hello2")
public String hello2(@ApiParam("用戶名") String username){
    return "hello"+username;
}

2.4 重啟程序查看注釋位置

2.5 Swagger注解簡單說明: 

  • Swagger的所有注解定義在io.swagger.annotations包下
  • @Api(tags = "xxx模塊說明") 作用在模塊類上
  • @ApiOperation("xxx接口說明") 作用在接口方法上
  • @ApiModel("xxxPOJO說明") 作用在模型類上:如VO、BO
  • @ApiModelProperty(value = "xxx屬性說明",hidden = true) 作用在類方法和屬性上,hidden設置為true可以隱藏該屬性
  • @ApiParam("xxx參數說明") 作用在參數、方法和字段上,類似@ApiModelProperty


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM