返回顶部

收藏

DynamicProxy模拟Spring AOP

更多

DynamicProxy模拟Spring AOP

package cn.outofmemory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;

interface Hello {
         void sayHello(String name);
}

 class MyHello implements Hello {
        public void sayHello(String name) {
              System.out.println("Hello " + name);
          }
 }

enum Level {
    INFO,DEBUGE;
}

class Logger {
    public static void logging(Level level, String context) {
        if (level.equals(Level.INFO)) {
            System.out.println(new Date()+ " " + context);
        }
        if (level.equals(Level.DEBUGE)) {
            System.out.println(new Date() + " " + context);
        }
    }

}

 class DynaProxyHello implements InvocationHandler {

         private Object delegate;

         public Object bind(Object delegate) {
             this.delegate = delegate;
             return Proxy.newProxyInstance(this.delegate.getClass().getClassLoader(), this.delegate.getClass().getInterfaces(), this);
         }

          public Object invoke(Object proxy, Method method, Object[] args)
                  throws Throwable {
              Object result = null;
              try {
                  //执行原来的方法之前记录日志
                  Logger.logging(Level.INFO, method.getName() + " Method Start!");
                  result = method.invoke(this.delegate, args);
               //执行原来的方法之后记录日志
                  Logger.logging(Level.DEBUGE, method.getName() + " Method end  .");
             } catch (Exception e) {
                  e.printStackTrace();
            }
              return result;
         }
}

public class AOPTest {
    public static void main(String[] args) {
                   Hello hello = (Hello)new DynaProxyHello().bind(new MyHello());
                  hello.sayHello(" Spring AOP");
              }
}

标签:java,spring,aop,代理

收藏

0人收藏

支持

0

反对

0

发表评论