在Java程序设计中,有两个特性非常重要,一个是IOC,另一个就是AOP。IOC应用非常广泛,这里就不说了,AOP应用得比较少,原理剖析得也比较少。今天写了一个AOP的例子来帮助分析AOP的原理。AOP是通过动态代理来实现的,任何一个动态代理的类必须实现InvocationHandler这个接口,这个接口的唯一方法-Invoke即函数调用的入口。通常我们需要使用AOP的类需要实现一个接口,方便注入到动态代理类中,这样也方便做扩展(其实还是使用了IOC的一些东西),这样的方式能够确保AOP的灵活性。
1.Process接口
public interface Process {
public void Start();
public void Action(String message);
}
2.ProcessImple类实现
Process接口
public class ProcessImple implements Process {
@Override
public void Start() {
// TODO Auto-generated method stub
System.out.println("process start.");
}
@Override
public void Action(String message) {
// TODO Auto-generated method stub
System.out.println("process: " + message);
}
<pre name="code" class="java">import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class ProxyClient {
public static void main(String[] args){
Process processImpl = new ProcessImple();
InvocationHandler handler= new DynamicProxy(processImpl);
Process process = (Process)Proxy.newProxyInstance(handler.getClass().getClassLoader(), processImpl
.getClass().getInterfaces(), handler);
//System.out.println(subject.getClass().getName());
process.Start();
process.Action("GET ALL MONEY.");
}
}
} 3.DynamicProxy(动态代理类)
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicProxy implements InvocationHandler {
private Object process;
public DynamicProxy(Object process){
this.process = process;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("before process.");
//System.out.println("Method:" + method);
method.invoke(process, args);
System.out.println("after process");
return null;
}
}
4.ProxyClient(调用类)
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class ProxyClient {
public static void main(String[] args){
Process processImpl = new ProcessImple();
InvocationHandler handler= new DynamicProxy(processImpl);
Process process = (Process)Proxy.newProxyInstance(handler.getClass().getClassLoader(), processImpl
.getClass().getInterfaces(), handler);
//System.out.println(subject.getClass().getName());
process.Start();
process.Action("GET ALL MONEY.");
}
}
运行下,看输出结果:
before process.
process start.
after process
before process.
process: GET ALL MONEY.
after process
这时候我们可以看到动态代理里面的方法都被调用了,AOP非常适合做日志功能,类似ASP.NET MVC里面的filter功能。