如何根据传递给方法的参数从 Aspect 执行 @Before

How to execute @Before from Aspect depending on passed parameter to method

我已经实现了检查用户是否为高级用户的方面,并根据该方面抛出匹配的异常。我会检查方法上的自定义注释。我将从 securityContext 中获取用户并这样做:

@Before(value = "@annotation(com.selfcast.annotation.RequiresBasic)")
public void requirePremiumForAction() {
    var talent = Optional.of((JwtAuthentication) SecurityContextHolder.getContext()
            .getAuthentication())
            .map(authUtil::getCredentials)
            .map(x -> userService.whoAmTalent(x.getEmail()))
            .orElseThrow(NoSuchTalent::new);

        if (
                paymentLaunchService.hasPaymentLaunchedInCountry(talent.getCountry().getId()) &&
                !talent.getAccountKind().equals(AccountKind.BASIC) &&
                !talent.getAccountKind().equals(AccountKind.FREEMIUM)
        ) {
            throw new ActionRequiresPremium();
        }
}

当我想根据方法接收的参数执行此操作时,我该如何继续?我需要根据其 ID 获取一个对象,检查该对象的 属性,然后才 return 一个 ActionRequiresPremium 异常。像这样:

@RequiresBasic
public Object doSomething(String Id){
  
}

这可能吗?据我研究,事实并非如此。但是使用@After 之类的东西似乎毫无意义。如果这不可能,有什么好的替代方案?

您可以使用JoinPoint as an argument in your advice. When you have that you can use the getArgs方法获取被调用方法的参数。

@Before(value = "@annotation(com.selfcast.annotation.RequiresBasic)")
public void requirePremiumForAction(JoinPoint jp) {
    var args = jp.getArgs(); // Now do your thing with the arguments as needed
    ... Remainder ommitted
}