Check Logic In After Returning Advice : AfterReturningAdvice « Spring « Java Tutorial






File: Main.java

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.framework.ProxyFactory;

public class Main {
  public static void main(String[] args) {
    KeyGenerator target = new KeyGenerator();

    ProxyFactory factory = new ProxyFactory();
    factory.setTarget(target);
    factory.addAdvice(new WeakKeyCheckAdvice());

    KeyGenerator keyGen = (KeyGenerator) factory.getProxy();

    System.out.println("Key: " + keyGen.getKey());
  }
}

class KeyGenerator {
  public static final long WEAK_KEY = 1L;

  public static final long STRONG_KEY = 2L;

  public long getKey() {
    return WEAK_KEY;
    // return STRONG_KEY;
  }
}

class WeakKeyCheckAdvice implements AfterReturningAdvice {

  public void afterReturning(Object returnValue, Method method, Object[] args, Object target)
      throws Throwable {

    if ((target instanceof KeyGenerator) && ("getKey".equals(method.getName()))) {
      long key = (Long) returnValue;

      if (key == KeyGenerator.WEAK_KEY) {
        System.out.println("a weak key");
      }
    }
  }
}
  Download:  Spring-CheckLogicInAfterReturningAdvice.zip( 4,745 k)








28.51.AfterReturningAdvice
28.51.1.Check Logic In After Returning Advice
28.51.2.After Returning Advice