java模拟实现spring的AOP
2012-11-15 15:48:45 来源:WEB开发网核心提示:package com.s2sh.intercepetor; public interface IHello { public void sayHello(String name); public void sayGoogBye(String name); } package com.
package com.s2sh.intercepetor; public interface IHello { public void sayHello(String name); public void sayGoogBye(String name); } package com.s2sh.intercepetor; public class Hello implements IHello { public void sayGoogBye(String name) { // TODO Auto-generated method stub System.out.println(name+" GoodBye!"); } public void sayHello(String name) { // TODO Auto-generated method stub System.out.println("Hello " + name); } } package com.s2sh.intercepetor; public class Logger { public static void before() { System.out.println("开始了"); } public static void after() { System.out.println("结束了"); } } package com.s2sh.intercepetor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DynaProxyHello implements InvocationHandler { private Object delegate;//被代理的对象 public DynaProxyHello(Object delegate) { this.delegate = delegate; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub Object result = null; try { // 执行原来的方法之前记录日志 Logger.before(); // JVM通过这条语句执行原来的方法(反射机制) result = method.invoke(this.delegate, args); // 执行原来的方法之后记录日志 Logger.after(); } catch (Exception e) { e.printStackTrace(); } // 返回方法返回值给调用者 return result; } } package com.s2sh.intercepetor; import java.lang.reflect.Proxy; public class Test { public static void main(String[] args) { // ①目标业务类 IHello target = new Hello(); // ② 将目标业务类和横切代码编织到一起 DynaProxyHello handler = new DynaProxyHello(target); // 创建代理类 IHello proxy = (IHello) Proxy.newProxyInstance( target.getClass().getClassLoader(), //返回目标类的类装载器,保持两个类的类装载器一样 target.getClass().getInterfaces(), //返回目标类实现的接口,保证组合而成的代理类也实现这些接口 handler//指派谁去处理方法的对象 ); // ④ 操作代理实例 proxy.sayHello("张三"); proxy.sayGoogBye("李四"); } }
更多精彩
赞助商链接