2015-09-03 7 views
7

Ist es möglich, Verfahren Argumentwert auf Grundlage einiger Prüfung vor der Ausführung mit Spring AOPFrühling AOP Änderungswert von Methoden Argument um Rat

Meine Methode

public String doSomething(final String someText, final boolean doTask) { 
    // Some Content 
    return "Some Text"; 
} 

Tipps Methode sich ändern

public Object invoke(final MethodInvocation methodInvocation) throws Throwable { 
    String methodName = methodInvocation.getMethod().getName(); 

    Object[] arguments = methodInvocation.getArguments(); 
    if (arguments.length >= 2) { 
     if (arguments[0] instanceof String) { 
      String content = (String) arguments[0]; 
      if(content.equalsIgnoreCase("A")) { 
       // Set my second argument as false 
      } else { 
       // Set my second argument as true 
      } 
     } 
    } 
    return methodInvocation.proceed(); 
} 

Bitte machen Sie mir die Möglichkeit, die Methode Argument valu einstellen e da es keine Einstelloptionen für das Argument gibt.

Antwort

3

bekam ich meine Antwort MethodInvocation

mit
public Object invoke(final MethodInvocation methodInvocation) throws Throwable { 
    String methodName = methodInvocation.getMethod().getName(); 

    Object[] arguments = methodInvocation.getArguments(); 
    if (arguments.length >= 2) { 
     if (arguments[0] instanceof String) { 
      String content = (String) arguments[0]; 
      if(content.equalsIgnoreCase("A")) { 
       if (methodInvocation instanceof ReflectiveMethodInvocation) { 
        ReflectiveMethodInvocation invocation = (ReflectiveMethodInvocation) methodInvocation; 
        arguments[1] = false; 
        invocation.setArguments(arguments); 
       } 
      } else { 
       if (methodInvocation instanceof ReflectiveMethodInvocation) { 
        ReflectiveMethodInvocation invocation = (ReflectiveMethodInvocation) methodInvocation; 
        arguments[1] = true; 
        invocation.setArguments(arguments); 
       } 
      } 
     } 
    } 
    return methodInvocation.proceed(); 
} 
6

Ja, das ist möglich. Sie benötigen ein ProceedingJoinPoint und statt:

methodInvocation.proceed(); 

Sie können dann mit den neuen Argumenten aufrufen gehen, zum Beispiel:

methodInvocation.proceed(new Object[] {content, false}); 

siehe http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/aop.html#aop-ataspectj-advice-proceeding-with-the-call

+1

Seien Sie einfach vorsichtig: Diese Dinge werden während ref leicht übersprungen Schauspielerei. Wenn Sie keine schöne Testsuite haben, kann es wehtun. –

+0

Ja, absolut! Die Argumente müssen übereinstimmen und die Refactoring-Tools werden in solchen Fällen nicht helfen. – reto

+0

Aber ich verwendete MethodInterceptor-Schnittstelle. Welche Änderungen muss ich für ProceedingJoinPoint vornehmen? –

Verwandte Themen