AOP(面向切面编程),官方定义就不讲了,可自行百度。按照我自己的理解就是,将代码片段动态的注入某一个已知的代码片段某一处。这样做的好处就是,在不改变原有代码情况下,又能扩充原有业务的功能。
AOP有两种实现方式:
1.动态代理
例子:
假设我们向给一个类的方法入口和出口各打印一行日志,但我们又不能改变原有代码
接口:
package com; public interface AlgorithmItf { void add(); void del(); void update(); void find(); }
实现:
package com; public class Algorithm implements AlgorithmItf { public void add() { System.out.println("add..."); } public void del() { System.out.println("del..."); } public void update() { System.out.println("update..."); } public void find() { System.out.println("find..."); } }
实现面向切面注入
package com; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class AopDyProxy<T> implements InvocationHandler { private T o; public T createInstance(T t) { o=t; return (T)(Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(), this)); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object re=null; System.out.println(method.getName()+" enter"); re=method.invoke(o, args); System.out.println(method.getName()+" exit"); return re; } public static void main(String[] args) { AopDyProxy<AlgorithmItf> p=new AopDyProxy<AlgorithmItf>(); AlgorithmItf a=p.createInstance(new Algorithm()); a.add(); a.update(); } }
测试结果输出
add enter
add...
add exit
update enter
update...
update exit
2.静态代理