我正在练习海关注释,我想创建一个自定义注释,将Math.random()值设置为@Entity字段(我知道我可以在构造函数中执行此操作,但我想使用注释)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.CONSTRUCTOR)
public @interface SetRandomPin {}
我的观点
@Around("@annotation(com.testingAnnotations.annotattions.SetRandomPin)")
public void setUserPin(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {....}
}
在我的@Entity中,当我在构造函数中放置@SetRandomPin时,方法setUserPin没有触发。
仅当我更改为ElementType.METHOD并将我的注释移动到UserService.class时,该方法才会触发。
我被困在这里,我无法理解为什么使用ElmentType而不是另一个。
默认Spring AOP不提供构造函数拦截或私有/受保护方法。你可以使用AspectJ来做到这一点。
来自docs
如果您的拦截需要包括目标类中的方法调用甚至构造函数,请考虑使用Spring驱动的本机AspectJ编织而不是Spring的基于代理的AOP框架。