探秘Spring AOP
一、织入的时机原理概述
1、编译期(AspectJ)
2、类加载时(AspectJ 5+)
3、运行时(Spring AOP)
运行时织入是怎么实现的?
1、从静态代理到动态代理
2、动态代理 分为 基于接口代理实现和基于继承代理实现
二 、代理模式
客户端通过代理对象渐渐与目标对象打交道,反之,目标对象委托代理对象与客户端进行交流。因此代理对象可以在目标对象方法前后,做出额外的操作,这就是代理AOP实现的原理。
代理模式类图
三 、代码演示
1、静态代理
- (1)目标对象:
public class RealSubject implements Subject {
@Override
public void request() {
System.out.println(" execute real subject request");
}
}
- (2)代理对象:
public class Proxy implements Subject {
private RealSubject realSubject;
public Proxy(RealSubject realSubject) {
this.realSubject = realSubject;
}
@Override
public void request() {
System.out.println(" before 织入逻辑");
try {
realSubject.request();
} catch (Exception e) {
System.out.println("ex:"+e.getMessage());
e.printStackTrace();
} finally {
System.out.println(" after 织入逻辑");
}
}
}
- (3)客户端调用接口
public interface Subject {
public void request();
}
- (4)客户端调用
public class Client {
public static void main(String[] args) {
Subject subject = new Proxy(new RealSubject());
subject.request();
}
}
2、动态代理
- (1) 动态代理
import cn.evchar.proxy.aop.RealSubject;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class JdkProxySubject implements InvocationHandler {
private RealSubject realSubject;
public JdkProxySubject(RealSubject realSubject) {
this.realSubject = realSubject;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object res = null;
System.out.println("before");
try {
res = method.invoke(realSubject,args);
} catch (Exception e) {
System.out.println("ex: "+e);
throw e;
} finally {
System.out.println("after");
}
return res;
}
}
- (2)客户端调用
import cn.evchar.proxy.aop.RealSubject;
import cn.evchar.proxy.aop.Subject;
import java.lang.reflect.Proxy;
public class Client {
public static void main(String[] args) {
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
Subject subject = (Subject) Proxy.newProxyInstance(Client.class.getClassLoader(),
new Class[]{Subject.class},new JdkProxySubject(new RealSubject()));
subject.request();
subject.hello();
}
}