swagger 常用注解
时间: 2025-03-08 07:09:23 浏览: 80
<think>好的,用户想了解Swagger中常用的注解及其用法。首先我需要回忆一下Swagger相关的知识,特别是常用的注解。根据提供的引用内容,引用[2]、[3]、[4]都提到了Swagger的常用注解,比如@Api、@ApiOperation、@ApiModel等。
首先,我应该整理出每个注解的作用和使用场景。比如@Api用于描述整个控制器类,@ApiOperation描述单个接口,@ApiParam用于参数说明。可能需要分点列出每个注解的示例,这样用户看起来更清晰。
然后要注意引用标注,每个注解的说明后面需要加上对应的引用来源。例如,@Api在引用[4]中有提到,@ApiOperation在引用[3]和[4]都有涉及。需要确认每个注解的信息在哪个引用里,正确标注。
接下来,用户可能需要示例代码,这样他们可以更好地理解如何使用这些注解。比如在控制器类上使用@Api,在方法上使用@ApiOperation,在模型类上使用@ApiModel。代码示例需要符合中文注释,并且语法正确。
另外,用户可能还会关心如何配置Swagger,但问题主要集中在注解上,所以配置部分可能不需要详细展开,但可以简要提及,如引用[2]提到的配置类和@EnableSwagger2注解。
最后,根据用户提供的示例结构,生成相关问题,比如如何配置Swagger、注解的作用范围等。确保问题与当前主题相关,帮助用户进一步探索。
需要检查是否有遗漏的重要注解,比如@ApiResponse、@ApiImplicitParam等,确保覆盖常用注解。同时,注意避免错误的信息,例如参数类型是否正确,示例代码是否合理。
总结步骤:整理常用注解列表,每个注解的作用、属性、示例代码,正确引用来源,最后生成相关问题。</think>### Swagger常用注解及示例
#### 1. **控制器类注解**
- **@Api**
描述控制器类的基本信息,作用于类级别。
```java
@Api(tags = "用户管理", description = "用户相关操作接口")
@RestController
public class UserController {
//...
}
```
属性:`tags`(接口分组名称)、`description`(描述)[^4]。
#### 2. **接口方法注解**
- **@ApiOperation**
描述单个接口的功能,作用于方法级别。
```java
@ApiOperation(value = "创建用户", notes = "根据User对象创建新用户")
@PostMapping("/user")
public User createUser(@RequestBody User user) {
//...
}
```
属性:`value`(接口名称)、`notes`(详细说明)[^3]。
- **@ApiResponses** 与 **@ApiResponse**
定义接口的响应状态码及说明。
```java
@ApiResponses({
@ApiResponse(code = 200, message = "请求成功"),
@ApiResponse(code = 400, message = "参数错误")
})
```
#### 3. **参数注解**
- **@ApiParam**
描述接口参数的详细信息,作用于方法参数。
```java
@ApiOperation("根据ID查询用户")
@GetMapping("/user/{id}")
public User getUser(
@ApiParam(name = "id", value = "用户ID", required = true)
@PathVariable Long id
) {
//...
}
```
属性:`name`(参数名)、`value`(描述)、`required`(是否必填)[^3]。
- **@ApiImplicitParam**
非绑定到方法参数的描述(如通过请求头传递参数)。
```java
@ApiImplicitParam(name = "token", value = "认证令牌", required = true, dataType = "string", paramType = "header")
```
#### 4. **模型类注解**
- **@ApiModel** 与 **@ApiModelProperty**
描述数据模型及其字段,作用于实体类。
```java
@ApiModel(description = "用户实体类")
public class User {
@ApiModelProperty(value = "用户ID", example = "1")
private Long id;
@ApiModelProperty(value = "用户名", required = true, example = "admin")
private String username;
}
```
属性:`value`(字段描述)、`example`(示例值)、`required`(是否必填)[^4]。
---
### 配置Swagger的示例
启用Swagger并配置基本信息:
```java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API文档")
.description("用户管理接口")
.version("1.0")
.build();
}
}
```
(配置类参考自[^2][^4])
---
阅读全文
相关推荐



















