知道Spring的都知道Spring的切面编程AOP(Aspect Oriented Programming),这里我们不讲Spring的切面,后面有机会我们再来解剖Spring的切面编程,我们想讲解一下普通的Java代码中怎么实现AOP,有两种方式实现AOP切面,一种是原生SDK实现,一种是基于三方包cglib。
先介绍一下JDK原生的,JDK原生的是基于接口编程:
先定义一个接口:
public interface ISayHelloWorld {
public String say();
}
实现这个接口:
public class ManSayHelloWorld implements ISayHelloWorld {
@Override
public String say() {
System.out.println("Hello world!");
return "MAN";
}
}
实现ManSayHelloWorld的切面代理,原生的AOP需要实现InvocationHandler接口,才能实现AOP。
public class SayHello {
public void say(){
System.out.println(“hello world!”);
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class AOPHandle implements InvocationHandler {
private Object obj;
AOPHandle(Object obj){
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
//方法返回值
System.out.println("前置代理");
//反射调用方法
Object ret=method.invoke(obj, args);
//声明结束
System.out.println("后置代理");
//返回反射调用方法的返回值
return ret;
}
}
测试这个代码:
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
ManSayHelloWorld sayHelloWorld = new ManSayHelloWorld();
AOPHandle handle = new AOPHandle(sayHelloWorld);
ISayHelloWorld i = (ISayHelloWorld) Proxy.newProxyInstance(ManSayHelloWorld.class.getClassLoader(), new Class[] { ISayHelloWorld.class }, handle);
i.say();
}
}
CSDN:java AOP编程