java使用动态代理来实现AOP(日志记录)
以下内容为原创,转载时请注明链接地址:http://www.cnblogs.com/tiantianbyconan/p/3336627.html
AOP(面向方面)的思想,就是把项目共同的那部分功能分离开来,比如日志记录,避免在业务逻辑里面夹杂着跟业务逻辑无关的代码。
下面是一个AOP实现的简单例子:
首先定义一些业务方法:
1 /**2 * Created with IntelliJ IDEA.
3 * Author: wangjie email:tiantian.china.2@gmail.com
4 * Date: 13-9-23
5 * Time: 下午3:49
6 */
7 public interface BussinessService {
8 public String login(String username, String password);
9 public String find();
10 }
11
12 public class BussinessServiceImpl implements BussinessService {
13 private Logger logger = Logger.getLogger(this.getClass().getSimpleName());
14
15 @Override
16 public String login(String username, String password) {
17 return "login success";
18 }
19
20 @Override
21 public String find() {
22 return "find success";
23 }
24
25 }
1 /**2 * Created with IntelliJ IDEA.
3 * Author: wangjie email:tiantian.china.2@gmail.com
4 * Date: 13-9-24
5 * Time: 上午10:27
6 */
7 public interface WorkService {
8 public String work();
9 public String sleep();
10 }
11
12 public class WorkServiceImpl implements WorkService{
13 @Override
14 public String work() {
15 return "work success";
16 }
17
18 @Override
19 public String sleep() {
20 return "sleep success";
21 }
22 }
实现InvocationHandler接口,使用map来存储不同的InvocationHandler对象,避免生成过多。
1 package com.wangjie.aoptest2.invohandler;2
3 import java.lang.reflect.InvocationHandler;
4 import java.lang.reflect.Method;
5 import java.lang.reflect.Proxy;
6 import java.util.Arrays;
7 import java.util.HashMap;
8 import java.util.logging.Logger;
9
10 /**
11 * Created with IntelliJ IDEA.
12 * Author: wangjie email:tiantian.china.2@gmail.com
13 * Date: 13-9-23
14 * Time: 下午3:47
15 */
16 public class LogInvoHandler implements InvocationHandler{
17 private Logger logger = Logger.getLogger(this.getClass().getSimpleName());
18
19 private Object target; // 代理目标
20 private Object proxy; // 代理对象
21
22 private static HashMap<Class<?>, LogInvoHandler> invoHandlers = new HashMap<Class<?>, LogInvoHandler>();
23
24 private LogInvoHandler() {
25 }
26
27 /**
28 * 通过Class来生成动态代理对象Proxy
29 * @param clazz
30 * @return
31 */
32 public synchronized static<T> T getProxyInstance(Class<T> clazz){
33 LogInvoHandler invoHandler = invoHandlers.get(clazz);
34
35 if(null == invoHandler){
36 invoHandler = new LogInvoHandler();
37 try {
38 T tar = clazz.newInstance();
39 invoHandler.setTarget(tar);
40 invoHandler.setProxy(Proxy.newProxyInstance(tar.getClass().getClassLoader(),
41 tar.getClass().getInterfaces(), invoHandler));
42 } catch (Exception e) {
43 e.printStackTrace();
44 }
45 invoHandlers.put(clazz, invoHandler);
46
47 }
48
49 return (T)invoHandler.getProxy();
50 }
51
52 @Override
53 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
54
55 Object result = method.invoke(target, args); // 执行业务处理
56
57 // 打印日志
58 logger.info("____invoke method: " + method.getName()
59 + "; args: " + (null == args ? "null" : Arrays.asList(args).toString())
60 + "; return: " + result);
61
62
63 return result;
64 }
65
66 public Object getTarget() {
67 return target;
68 }
69
70 public void setTarget(Object target) {
71 this.target = target;
72 }
73
74 public Object getProxy() {
75 return proxy;
76 }
77
78 public void setProxy(Object proxy) {
79 this.proxy = proxy;
80 }
81 }
然后编写一个Test类测试:
1 /**2 * Created with IntelliJ IDEA.
3 * Author: wangjie email:tiantian.china.2@gmail.com
4 * Date: 13-9-24
5 * Time: 上午9:54
6 */
7 public class Test {
8 public static Logger logger = Logger.getLogger(Test.class.getSimpleName());
9 public static void main(String[] args) {
10
11 BussinessService bs = LogInvoHandler.getProxyInstance(BussinessServiceImpl.class);
12 bs.login("zhangsan", "123456");
13 bs.find();
14
15 logger.info("--------------------------------------");
16
17 WorkService ws = LogInvoHandler.getProxyInstance(WorkServiceImpl.class);
18 ws.work();
19 ws.sleep();
20
21 logger.info("--------------------------------------");
22
23 BussinessService bss = LogInvoHandler.getProxyInstance(BussinessServiceImpl.class);
24 bss.login("lisi", "654321");
25 bss.find();
26
27 }
28 }
以后需要添加新的业务逻辑XXXService,只需要调用
XXXService xs = LogInvoHandler.getProxyInstance(XXXServiceImpl.class);
即可。
也可以模仿Spring等框架的配置,把bean的类名配置在xml文件中,如:
<bean >
然后在java代码中解析xml,通过Class.forName("com.wangjie.aoptest2.service.impl.BussinessServiceImpl");获得Class对象
然后通过LogInvoHandler.getProxyInstance(Class.forName("com.wangjie.aoptest2.service.impl.BussinessServiceImpl"));获得代理对象Proxy
再使用反射去调用代理对象的方法。
运行结果如下:
九月 24, 2013 11:08:03 上午 com.wangjie.aoptest2.invohandler.LogInvoHandler invoke
INFO: ____invoke method: login; args: [zhangsan, 123456]; return: login success
九月 24, 2013 11:08:03 上午 com.wangjie.aoptest2.invohandler.LogInvoHandler invoke
INFO: ____invoke method: find; args: null; return: find success
九月 24, 2013 11:08:03 上午 com.wangjie.aoptest2.Test main
INFO: --------------------------------------
九月 24, 2013 11:08:03 上午 com.wangjie.aoptest2.invohandler.LogInvoHandler invoke
INFO: ____invoke method: work; args: null; return: work success
九月 24, 2013 11:08:03 上午 com.wangjie.aoptest2.invohandler.LogInvoHandler invoke
INFO: ____invoke method: sleep; args: null; return: sleep success
九月 24, 2013 11:08:03 上午 com.wangjie.aoptest2.Test main
INFO: --------------------------------------
九月 24, 2013 11:08:03 上午 com.wangjie.aoptest2.invohandler.LogInvoHandler invoke
INFO: ____invoke method: login; args: [lisi, 654321]; return: login success
九月 24, 2013 11:08:03 上午 com.wangjie.aoptest2.invohandler.LogInvoHandler invoke
INFO: ____invoke method: find; args: null; return: find success
以上是 java使用动态代理来实现AOP(日志记录) 的全部内容, 来源链接: utcz.com/z/391590.html