预览加载中,请您耐心等待几秒...
1/10
2/10
3/10
4/10
5/10
6/10
7/10
8/10
9/10
10/10

在线预览结束,喜欢就下载吧,查找使用更方便

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

java使用动态代理来实现AOPjava使用动态代理来实现AOP下面是一个AOP实现的简单例子:首先定义一些业务方法:复制代码代码如下:/***CreatedwithIntelliJIDEA.*Author:wangjieemail:tiantian.china.2@gmail.com*Date:13-9-23*Time:下午3:49*/publicinterfaceBussinessService{publicStringlogin(Stringusername,Stringpassword);publicStringfind();}publicclassBussinessServiceImplimplementsBussinessService{privateLoggerlogger=Logger.getLogger(this.getClass().getSimpleName());@OverridepublicStringlogin(Stringusername,Stringpassword){return"loginsuccess";}@OverridepublicStringfind(){return"findsuccess";}}复制代码代码如下:/***CreatedwithIntelliJIDEA.*Author:wangjieemail:tiantian.china.2@gmail.com*Date:13-9-24*Time:上午10:27*/publicinterfaceWorkService{publicStringwork();publicStringsleep();}publicclassWorkServiceImplimplementsWorkService{@OverridepublicStringwork(){return"worksuccess";}@OverridepublicStringsleep(){return"sleepsuccess";}}实现InvocationHandler接口,使用map来存储不同的InvocationHandler对象,避免生成过多。复制代码代码如下:packagecom.wangjie.aoptest2.invohandler;importjava.lang.reflect.InvocationHandler;importjava.lang.reflect.Method;importjava.lang.reflect.Proxy;importjava.util.Arrays;importjava.util.HashMap;importjava.util.logging.Logger;/***CreatedwithIntelliJIDEA.*Author:wangjieemail:tiantian.china.2@gmail.com*Date:13-9-23*Time:下午3:47*/publicclassLogInvoHandlerimplementsInvocationHandler{privateLoggerlogger=Logger.getLogger(this.getClass().getSimpleName());privateObjecttarget;//代理目标privateObjectproxy;//代理对象privatestaticHashMap<Class,LogInvoHandler>();privateLogInvoHandler(){}/***通过Class来生成动态代理对象Proxy*@paramclazz*@return*/publicsynchronizedstaticTgetProxyInstance(Classclazz){LogInvoHandlerinvoHandler=invoHandlers.get(clazz);if(null==invoHandler){invoHandler=newLogInvoHandler();try{Ttar=clazz.newInstance();invoHandler.setTarget(tar);invoHandler.setProxy(Proxy.newProxyInstance(tar.getClass().getClassLoader(),tar.getClass().getInterfaces(),invoHandler));}catch(Exceptione){e.printStackTrace();}invoHandlers.put(clazz,invoHandler);}re