【问题标题】:How to execute @Before from Aspect depending on passed parameter to method如何根据传递给方法的参数从 Aspect 执行 @Before
【发布时间】:2021-06-22 09:30:20
【问题描述】:

我有一个实现的方面,它检查用户是否是高级用户,并且根据它我可以抛出一个匹配的异常。我会检查方法上的自定义注释。我会从 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 获取对象,检查该对象的属性,然后才返回 ActionRequiresPremium 异常。像这样:

@RequiresBasic
public Object doSomething(String Id){
  
}

这甚至可能吗?据我研究,它不是。然而,使用 @After 之类的东西似乎毫无意义。如果无法做到这一点,有什么好的替代方案?

【问题讨论】:

  • 您可以使用JoinPoint 作为参数,然后您可以调用getArgs
  • @M.Deinum 我认为在方法执行之前我无法访问这些参数。不过你是对的,它有效。谢谢!请将您的答案作为回复发布,以便我将其标记为正确。

标签: java spring aspect


【解决方案1】:

您可以在建议中使用JoinPoint 作为参数。当你拥有它时,你可以使用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
}

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 2020-09-18
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 2018-11-02
    • 2011-07-18
    • 2021-05-26
    相关资源
    最近更新 更多