【问题标题】:What Guice MethodInterceptor should returnGuice MethodInterceptor 应该返回什么
【发布时间】:2015-06-19 09:50:35
【问题描述】:

我试图找到 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
            }
    }
}

感谢您的帮助。

【问题讨论】:

  • 顺便说一句:将用户注入方法拦截器时会遇到问题,因为您必须在 bind() 期间自己实例化拦截器 ...

标签: java guice guice-3


【解决方案1】:

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

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

【讨论】:

  • 是的,你是对的,但是我返回任何对象的结果都是一样的,以我的方式,不需要创建异常并捕获它。所以这是更简单的方法。
  • 返回 null 可能有点冒险,因为调用者可能会使用该对象,然后您将在运行时遇到 NullPointerExceptions。如果您使用的是 Java8,则可以考虑将方法更改为返回 Optional,然后您的拦截器可以将其返回为空。
  • ok null 是有风险的,但是返回 MethodInvocation 和任何其他对象有什么区别(return new Object();)
  • new Object() 可能会导致 ClassCastException,除非方法的返回类型是 Object
  • 同意。我绝对建议切换到 Option。
猜你喜欢
  • 2017-08-24
  • 2019-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-04
相关资源
最近更新 更多