标签:
public interface InvocationHandler { public Object invoke(Object proxy,Method method,Object[] args) throws Throwable; }
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException
public class ForumServiceImpl implements ForumService{ public void removeTopic(int topicId){ //①在此位置原有的横切代码被移除(抽取切面中) System.out.println("模拟删除Topic记录:"+topicId); try{ Thread.currentThread().sleep(20); }catch(Exception e){ throw new RuntimeException(e); } //①在此位置原有的横切代码被移除(抽取切面中) } public void removeForum(int forumId){ //②在此位置原有的横切代码被移除(抽取切面中) System.out.println("模拟删除Forum记录:"+forumId); try{ Thread.currentThread().sleep(40); }catch(Exception e){ throw new RuntimeException(e); } //②在此位置原有的横切代码被移除(抽取切面中) } }
public class PerformanceHandler implements InvocationHandler{ private Object target; //target为目标业务类 public PerformanceHandler(Object target){ this.target=target; } public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{ PerformanceMonitor.begin(target.getClass().getName()+"."+method.getName()); //③ Object obj=method.invoke(target, args); //⑤通过反射调用业务类的目标方法 PerformanceMonitor.end(); //④ return obj; } }
import java.lang.reflect.Proxy; public class TestForumService { public static void main(String[] args){ ForumService target=new ForumServiceImpl(); //被代理对象 PerformanceHandler handler=new PerformanceHandler(target); //将目标业务类和横切代码编织到一起 ForumService proxy=(ForumService)Proxy.newProxyInstance( //创建代理实例 target.getClass().getClassLoader, target.getClass().getInstances(), handler); proxy.removeForum(10); proxy.removeTopic(1012); } }
import class CglibProxy implements MethodInterceptor{ private Enhancer enhancer = new Enhancer(); public Object getProxy(Class clazz){ enhancer.setSuperclass(clazz); //设置需要创建子类的类 enhancer.setCallback(this); return enhancer.create(); //通过字节码技术动态创建子类实例 } public Object intercept(Object obj,Method method,Object[] args,MethodProxy proxy) throws Throwable{//拦截父类所有方法的调用 PerformanceMonitor.begin(obj.getClass().getName()+"."+method.getName()); //① Object result = proxy.invokeSuper(obj,args); //通过代理类调用父类中的方法 PerformanceMonitor.end(); //② return result; } }
import java.lang.reflect.Proxy; public class TestForumService{ public static void main(String[] args){ CglibProxy proxy = new CglibProxy(); ForumServiceImpl forumService = (ForumServiceImpl)proxy.getProxy(ForumServiceImpl.class); //动态生成子类的方式创建代理类 forumService.removeForum(10); forumService.removeTopic(1023); } }
标签:
原文地址:http://www.cnblogs.com/xujiming/p/5737531.html