Java Tutorial/Spring/AfterReturningAdvice

Материал из Java эксперт
Версия от 15:22, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

After Returning Advice

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) throws Exception {
    MessageWriter target = new MessageWriter();
    // create the proxy
    ProxyFactory pf = new ProxyFactory();
    pf.addAdvice(new SimpleAfterReturningAdvice());
    pf.setTarget(target);
    MessageWriter proxy = (MessageWriter) pf.getProxy();
    // write the messages
    proxy.writeMessage();
  }
}
class MessageWriter {
  public void writeMessage() {
      System.out.println("A");
  }
}
class SimpleAfterReturningAdvice implements AfterReturningAdvice {
  public void afterReturning(Object returnValue, Method method, Object[] args,
          Object target) throws Throwable {
      System.out.println("After method: " + method.getName());
  }
}





Check Logic In After Returning Advice

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");
      }
    }
  }
}