java-aop
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.静态代理,直接上例子了(摘自网络)
/** * 静态代理可通过接口或者类进行代理 * */ public class StaticProxyTest { public static void main(String[] args) { //基于接口 MyPhone myPhone = new MyPhoneImpl(); StaticProxy proxy = new StaticProxy(myPhone); proxy.name("华为"); //基于类 MyPhoneClass myPhoneClass = new MyPhoneClass(); ProxyEntity entity = new ProxyEntity(myPhoneClass); entity.name("小米"); } } /** * 接口 * */ interface MyPhone{ public void name(String str); } /** * 接口实现类 * @author Administrator * */ class MyPhoneImpl implements MyPhone{ @Override public void name(String str) { System.out.println("早上好"+str); } } /** * 自定义静态代理类 * @author Administrator * */ class StaticProxy implements MyPhone{ MyPhone myPhone; public StaticProxy(MyPhone myPhone) { this.myPhone = myPhone; } @Override public void name(String str) { beforeFun(); myPhone.name(str); afterFun(); } public void beforeFun(){ System.out.println("前置代理"); } public void afterFun(){ System.out.println("后置代理"); } } /** * 实体类 * @author Administrator * */ class MyPhoneClass{ public void name(String str){ System.out.println("基于类实现:"+str); } } /** * 基于类的代理 * @author Administrator * */ class ProxyEntity extends MyPhoneClass{ MyPhoneClass myPhone; public ProxyEntity(MyPhoneClass myPhone) { this.myPhone = myPhone; } @Override public void name(String str) { beforeFun(); myPhone.name(str); afterFun(); } public void beforeFun(){ System.out.println("前置代理"); } public void afterFun(){ System.out.println("后置代理"); } }