Skip to content

后端注解使用

本文档介绍后端常用注解的使用方法。

限流注解

@RateLimit

用于接口限流,防止恶意请求。

java
@RateLimit(count = 10, time = 60, limitType = RateLimit.LimitType.IP)
@PostMapping("/send")
public R<Void> sendSms() {
    return R.ok();
}

参数说明:

  • count:限制次数
  • time:时间窗口(秒)
  • limitType:限流类型(IP / USER / GLOBAL)

数据脱敏注解

@Desensitize

用于数据脱敏,保护敏感信息。

java
@Data
public class UserVO {
    @Desensitize(type = DesensitizeType.PHONE)
    private String phone;
    
    @Desensitize(type = DesensitizeType.ID_CARD)
    private String idCard;
    
    @Desensitize(type = DesensitizeType.EMAIL)
    private String email;
}

支持的脱敏类型:

  • PHONE:手机号
  • ID_CARD:身份证
  • EMAIL:邮箱
  • BANK_CARD:银行卡
  • NAME:姓名
  • ADDRESS:地址
  • PASSWORD:密码
  • CUSTOM:自定义

权限注解

@RequiresPermissions

用于权限控制。

java
@RequiresPermissions("system:user:add")
@PostMapping("/add")
public R<Void> add(@RequestBody User user) {
    return R.ok();
}

@RequiresRoles

用于角色控制。

java
@RequiresRoles("admin")
@DeleteMapping("/{id}")
public R<Void> delete(@PathVariable Long id) {
    return R.ok();
}

日志注解

@Log

用于记录操作日志。

java
@Log(title = "用户管理", businessType = BusinessType.INSERT)
@PostMapping("/add")
public R<Void> add(@RequestBody User user) {
    return R.ok();
}

数据权限注解

@DataScope

用于数据权限过滤。

java
@DataScope(deptAlias = "d", userAlias = "u")
@GetMapping("/list")
public R<List<User>> list() {
    return R.ok(userService.list());
}

参数验证注解

常用验证注解

java
@Data
public class UserDTO {
    @NotBlank(message = "用户名不能为空")
    private String username;
    
    @Email(message = "邮箱格式不正确")
    private String email;
    
    @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
    private String phone;
    
    @Min(value = 18, message = "年龄不能小于18岁")
    @Max(value = 60, message = "年龄不能大于60岁")
    private Integer age;
}

事务注解

@Transactional

用于事务管理。

java
@Transactional(rollbackFor = Exception.class)
@PostMapping("/add")
public R<Void> add(@RequestBody User user) {
    userService.save(user);
    return R.ok();
}

缓存注解

@Cacheable

用于缓存查询结果。

java
@Cacheable(value = "user", key = "#id")
@GetMapping("/{id}")
public R<User> getById(@PathVariable Long id) {
    return R.ok(userService.getById(id));
}

@CacheEvict

用于清除缓存。

java
@CacheEvict(value = "user", key = "#id")
@DeleteMapping("/{id}")
public R<Void> delete(@PathVariable Long id) {
    userService.removeById(id);
    return R.ok();
}

参考资源

MIT License