您的位置:首页 > 编程语言 > Java开发

Spring4学习笔记-AOP前传之动态代理

2016-02-04 11:02 567 查看
假设有如下需求:

    写一个计算器类,里面包含加减乘除四个方法。在每个方法开始前打印出该方法开始的消息,在每个方法结束前打印出该方法结束的消息和计算的结果。

普通方法,先写一个接口,然后在接口里实现四个方法。在每个方法里加上要打印的语句。实现代码如下。

ArithmeticCalculator接口
[code=java;toolbar:false">package com.spring.aop.helloworld;

public interface ArithmeticCalculator {
int add(int i, int j);

int sub(int i, int j);

int mul(int i, int j);

int div(int i, int j);
}ArithmeticCalculator  arithmeticCalculator = new ArithmeticCalculatorLoggingImpl();

arithmeticCalculator.add(1, 5);
System.out.println("----------");
arithmeticCalculator.sub(5, 3);
System.out.println("----------");
arithmeticCalculator.mul(3, 7);
System.out.println("----------");
arithmeticCalculator.div(9, 3);package com.spring.aop.helloworld;

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

public class ArithmeticCaculatorLogginProxy {
//要代理的对象
private ArithmeticCalculator target;

public ArithmeticCaculatorLogginProxy(ArithmeticCalculator target){
this.target = target;
}

public ArithmeticCalculator getLoggingProxy() {
ArithmeticCalculator proxy = null;
//代理对象由哪一个类加载器负责加载
ClassLoader loader = target.getClass().getClassLoader();
//代理对象的类型,即其中有哪些方法
Class[] interfaces = new Class[]{ArithmeticCalculator.class};
//当调用代理对象其中的方法时,该执行的代码
InvocationHandler h = new InvocationHandler() {
/**
 * proxy:正在返回的代理对象,一般情况下,在invoke方法中都不适用该对象
 * method:正在被调用的方法
 * args:调用方法时,传入的参数
 */
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//下面这句执行的时候又会调用invoke方法,所以会出现死循环导致内存溢出
//System.out.println(proxy.toString());
String methodName = method.getName();
//日志
System.out.println("The method " + methodName + " begins with" + Arrays.asList(args));
System.out.println("Invoke...");
//执行方法
Object result = method.invoke(target, args);
//日志
System.out.println("The method" + methodName + " ends with " + result);
return result;
}
};
proxy = (ArithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, h);
return proxy;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: