使用 Spring AOP 中的方面的方法的条件执行

Conditional execution of a method using Aspects in Spring AOP

我是 Spring AOP 的新手。仅当用户获​​得授权时,我才需要执行方法。 这是我的代码。

@Before("some pointcut")
public HttpStatus checkUserAuthentication(String userName)
{
   if( userAuthorized(userName) )
   {
       //go on executing method
   } else {
      return HttpStatus.FORBIDDEN; 
   } 
}

在使用 JoinPoint 时是否有 ProceedingJoinPoint.proceed 的替代方案,或者我可以将 ProceedingJoinPoint 与 @Before 建议一起使用吗?如果用户被授权,如何继续执行 if 语句。

我使用@Around 建议解决了这个问题。并将 return 类型更改为对象,以便它可以 return ProceedingJoinPoint 成功验证。

@Around("some pointcut")
public Object checkUserAuthentication(ProceedingJoinPoint pjp, String userName)
{
   if( userAuthorized(userName) )
   {
       return pjp.roceed();
   } else {
      return new ResponseEntity<>(HttpStatus.FORBIDDEN); 
   } 
}

使用@Around 作为通知,可以在验证后将控件传递给方法。