What Guice MethodInterceptor should return

1.7k views Asked by At

I am trying to find an answer what should be returned by Guice MethodInterceptor. What is difference between returning methodInvocation.proceed(); and returning null;

Here is my situation: in some cases user has right to invoke some method in some not. I want to implement this kind situation using guice aop.

What should I return if i don't want to invoke method? And what is the difference between returning null and any other object.

@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
   }
}

and here is Interceptor class:

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
            }
    }
}

Thanks for your help.

1

There are 1 answers

5
Diego Martinoia On

What you return is the result of the method. If you want to prevent the invocation, then you should either throw an exception or return some sort of "Unauthorized" message. Look here.

If you are using Java8+, I'd recommend as the best option to change the method signature to return an Optional instead of whatever type, and return it empty.