21xrx.com
2025-03-27 13:53:39 Thursday
文章检索 我的文章 写文章
Java自定义注解实现AOP校验实体类内的某个字段
2023-06-14 06:35:07 深夜i     35     0
Java 自定义注解 AOP 校验实体类

在Java开发中,我们经常需要校验实体类中某个字段的合法性,比如判断用户输入的手机号是否正确。传统的做法是在业务逻辑层做校验,但这种做法会导致代码重复、维护困难等问题。而使用AOP可以将校验逻辑从业务逻辑中抽离出来,提高代码的可重用性和可维护性。本文将介绍如何使用Java自定义注解实现AOP校验实体类内的某个字段。

具体实现思路如下:首先,定义一个注解,用于标识实体类中需要校验的字段。其次,定义一个切面,通过判断注解是否存在来判断是否需要校验。最后,在业务逻辑中调用校验方法即可。

下面是代码示例:

定义注解:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckField {
  String value() default "";
}

定义切面:

@Aspect
@Component
public class CheckFieldAspect {
  @Autowired
  private HttpServletRequest request;
  @Pointcut("@annotation(com.example.demo.annotation.CheckField)")
  public void checkField()
  
  @Before("checkField()")
  public void beforeCheckField(JoinPoint joinPoint) throws CheckFieldException {
    Object[] args = joinPoint.getArgs();
    CheckField checkField = getCheckFieldAnnotation(joinPoint);
    if (checkField != null) {
      for (Object arg : args) {
        String fieldValue = BeanUtils.getProperty(arg, checkField.value());
        if (StringUtils.isBlank(fieldValue)) {
          throw new CheckFieldException("字段" + checkField.value() + "不能为空!");
        }
      }
    }
  }
  private CheckField getCheckFieldAnnotation(JoinPoint joinPoint) {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    return method.getAnnotation(CheckField.class);
  }
}

定义异常:


public class CheckFieldException extends Exception {

  private static final long serialVersionUID = 1L;

  public CheckFieldException(String message) {

    super(message);

  }

}

在实体类中使用注解:


public class User {

  @CheckField("mobile")

  private String mobile;

  // 省略其他字段和getter/setter方法

}

在业务逻辑中调用校验方法:


@Service

public class UserService {

  @Autowired

  private UserRepository userRepository;

  public void addUser(User user) throws CheckFieldException {

    userRepository.save(user);

  }

}

  
  

评论区