1

我试图找到 Guice MethodInterceptor 应该返回的答案。返回 methodInvocation.proceed(); 有什么区别?并返回 null;

这是我的情况:在某些情况下,用户有权在某些情况下调用某些方法。我想使用 guice aop 来实现这种情况。

如果我不想调用方法,我应该返回什么?返回 null 和任何其他对象有什么区别。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AOPEstablisher{

}

class GuiceModule extends AbstractModule{
     @Override
     protected void configure() {

       GuiceExampleAop guiceExampleAop = new GuiceExampleAop ();
       requestInjection(guiceExampleAop);
       bindInterceptor(Matchers.any(),    Matchers.annotatedWith(AOPEstablisher.class),    guiceExampleAop );

  }
}


class CommandExecutor{
   @AOPEstablisher
   public void executeInSomeCases(){

      //I want to execute this command in some cases
   }
}

这是拦截器类:

import org.aopalliance.intercept.MethodInterceptor;

public class GuiceExampleAop implements MethodInterceptor {

    @Inject
    User user;

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {

            if(user.hasRigths(){
                return methodInvocation.proceed();
            else{
                return null?
                return methodInvocation?
                //what should be returned here?
                // what is difference between returning methodInvocation and null
            }
    }
}

谢谢你的帮助。

4

1 回答 1

2

你返回的是方法的结果。如果您想阻止调用,那么您应该抛出异常或返回某种“未经授权”消息。看这里

如果您使用的是 Java8+,我建议您将方法签名更改为返回 Optional 而不是任何类型并将其返回为空的最佳选择。

于 2015-06-19T10:06:36.040 回答