Swagger @ApiParam 與 @ApiModelProperty 區別

REST
Remote
0
08:04 AM · Dec 01 ,2025

1. 概述

在本教程中,我們將簡要了解 Swagger 的 @ApiParam@ApiModelProperty 註解。 此外,我們將比較這些註解並確定每種註解的正確用法。

2. 關鍵差異

簡單來説@ApiParam@ApiModelProperty 註解為 Swagger 添加了不同的元數據。 @ApiParam 註解用於 API 資源請求的參數,而 @ApiModelProperty 則用於模型屬性。

3.

The annotation is for use solely with the JAX-RS 1.x/2.x parameter annotations like , , , , and . Although swagger-core scans these annotations by default, we can use to add more details about the parameters or change the values as they are read from the code.

The annotation helps to specify the name, type, description (value), and example value of the parameter. Moreover, we can specify whether the parameter is required or optional.

Let’s look at its usage:

@RequestMapping(
    method = RequestMethod.POST,
    value = "/createUser",
    produces = "application/json; charset=UTF-8")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
@ApiOperation(value = "Create user",
  notes = "This method creates a new user")
public User createUser(
  @ApiParam(
    name =  "firstName",
    type = "String",
    value = "First Name of the user",
    example = "Vatsal",
    required = true)
  @RequestParam String firstName) {
 
    User user = new User(firstName);
    return user;}

Let’s look at the Swagger UI representation for our  example:

userimage

Now, let’s look at .

4. @ApiModelProperty

The @ApiModelProperty annotation allows us to control Swagger-specific definitions such as description (value), name, data type, example values, and allowed values for the model properties.

Also, it offers additional filtering properties in case we want to hide the property in certain scenarios.

Let’s add a few model properties to the User’s firstName field:

@ApiModelProperty(
  value = "first name of the user",
  name = "firstName",
  dataType = "String",
  example = "Vatsal")
String firstName;

Now, let’s take a look at the User Model’s specifications in Swagger UI:

usermodel

5. 結論

在本文中,我們探討了兩種 Swagger 註解,用於為參數和模型屬性添加元數據。我們還查看了使用這些註解的示例代碼,並觀察了它們在 Swagger UI 中的表示形式。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.