1、静态代码虽然简单易懂,但是要写一堆xxxProxy类。
2、使用动态代理,只要写一个Proxy类就可以了。
3、cglib采用asm在运行时动态修改类,除了final 不能代理,其它都可以。
4、aspectJ 属于编译期织入
5、spring aop 可以使用jdk动态代理,也可以使用cglib
package gaofeng;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/*
* JDK的动态代码,要求被代理的对象必须有interface
* CGLib就没有这个限制
*/
public class DynProxy {
public static void main(String[] args) {
Hello hello = (Hello) Proxy.newProxyInstance(
HelloImpl.class.getClassLoader(),
HelloImpl.class.getInterfaces(),
new Dproxy(new HelloImpl()));
hello.say("wwworld");
Hello hello2 = new Dproxy2(new HelloImpl()).getProxy();
hello2.say("hello2");
}
}
interface Hello{
public void say(String world);
}
class HelloImpl implements Hello{
@Override
public void say(String world) {
System.out.println("hello,"+world);
}
}
class Dproxy implements InvocationHandler{
public Dproxy(Object target) {
this.target = target;
}
private Object target;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("method:"+method);
before();
return method.invoke(target, args);
}
private void before() {
System.out.println("this is before");
}
}
class Dproxy2 implements InvocationHandler{
public Dproxy2(Object target) {
this.target = target;
}
private Object target;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
return method.invoke(target, args);
}
@SuppressWarnings("unchecked")
public <T> T getProxy() {
return (T) Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
this);
}
private void before() {
System.out.println("this is before");
}
}
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.6</version>
</dependency>
package gaofeng;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class CGlib {
public static void main(String[] args) {
Action333 action = new CGLibProxy().getProxy(Action333.class);
action.ddd("666");
}
}
class Action333 {
public void ddd(String action) {
System.out.println("do " + action);
}
}
class CGLibProxy implements MethodInterceptor{
@SuppressWarnings("unchecked")
public <T> T getProxy(Class<T> cls) {
return (T)Enhancer.create(cls, this);
}
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("method:"+method);
before();
return proxy.invokeSuper(obj, args);
}
private void before() {
System.out.println("this is before");
}
}