1. 使用动态代理解决上述问题
代理设计模式的原理:使用一个代理将对象包装起来,用该代理对象取代原始对象;任何对原始对象的调用都需要通过代理,代理对象决定是否以及何时将方法调用转到原始对象上。
ArithmeticCalculator.java:
package com.qiaobc.spring.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);
}
ArithmeticCalculatorImpl.java:
package com.qiaobc.spring.helloworld;
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
@Override
public int add(int i, int j) {
return i + j;
}
@Override
public int sub(int i, int j) {
return i - j;
}
@Override
public int mul(int i, int j) {
return i * j;
}
@Override
public int div(int i, int j) {
return i / j;
}
}
ArithmeticCalculatorLoggingProxy.java:
package com.qiaobc.spring.helloworld;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class ArithmeticCalculatorLoggingProxy {
// 要代理的对象
private ArithmeticCalculator target;
public ArithmeticCalculatorLoggingProxy(ArithmeticCalculator target) {
this.target = target;
}
public ArithmeticCalculator getLoggingProxy() {
ArithmeticCalculator proxy = null;
// 1). 代理对象由哪一个类加载器负责加载
ClassLoader loader = target.getClass().getClassLoader();
// 2). 代理对象的类型,即其中有哪些方法
Class<?>[] interfaces = new Class[]{ArithmeticCalculator.class};
// 3). 当调用代理对象的方法时,该执行的操作
InvocationHandler h = new InvocationHandler() {
/**
* proxy: 正在返回的代理对象,一般在invoke()方法中都不使用,容易造成死循环
* method: 正在被调用的方法
* args: 调用方法时传入的参数
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// System.out.println(proxy.toString());
String methodName = method.getName();
// 日志
System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
// 执行方法
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;
}
}
TestMain.java:
package com.qiaobc.spring.helloworld;
public class TestMain {
public static void main(String[] args) {
// ArithmeticCalculator calculator = null;
// calculator = new ArithmeticCalculatorLoggingImpl();
ArithmeticCalculator calculator = new ArithmeticCalculatorImpl();
ArithmeticCalculator proxy = new ArithmeticCalculatorLoggingProxy(calculator).getLoggingProxy();
int result = proxy.add(10, 20);
System.out.println("--> " + result);
result = proxy.mul(10, 20);
System.out.println("--> " + result);
}
}
2. AOP概述
面向切面编程(Aspect-Oriented Programming,简称AOP)是一种新的方法论,是对传统面向对象编程(Object-Oriented Programming,简称OOP)的补充。
AOP的主要编程对象是切面(aspect),而切面模块化横切关注点。其优势在于:每个事物逻辑位于一个位置,代码不分散,便于维护和升级;业务模块只包含核心代码,更为简洁。
在Java社区中,最完整且最流行的框架是AspectJ;而在Spring2.0以上版本中,可以使用基于AspectJ注解的方式或基于XML文件的方式来配置AOP。