Spring AOP概念
- AOP(Aspect Oriented Programming)是面向切面编程
就是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。简单说,就是在不改变方法源代码的基础上,对方法进行功能增强。本质上是生成了一个新的类,叫做代理类 - AOP对程序的扩展方式采用动态代理的方式(JDK动态代理和Cglib动态代理两种方式)
Spring动态代理
- JDK的动态代理
》Proxy类的静态方法可以创建代理对象
static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
》三个参数
参数1:ClassLoader loader类加载器,用来加载代理对象
参数2:Class<?>[] interfaces目标类的字节码对象数组。因为代理的是接口,需要知道接口中的所有方法
参数3:InvocationHandler h执行句柄,代理对象处理的核心逻辑就在该接口中
案例:老总吃饭
- TestJdkProxy
public class TestJdkProxy {
public static void main(String[] args){
//Jdk代理
LaoZong laoZong = new LaoZong();
MiShu miShu = new MiShu();
//创建一个代理类,创建该类的对象
ClassLoader classLoader= LaoZong.class.getClassLoader();
Class[] interfaces = new Class[]{
ILaoZong.class};
//处理器
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
miShu.laiBeiJiu();
Object returnValue = method.invoke(laoZong,args);
miShu.laiGenYan();
return returnValue;
}
};
ILaoZong iLaoZong = (ILaoZong) Proxy.newProxyInstance(classLoader,interfaces,handler);
iLaoZong.eat();
}
}
- 老总类
public void eat(){
System.out.println("eat san xia guo");
System.out.println("eat wa wa cai");
}
@Override
public void run() {
System.out.println("ao ao pao");
}
@Override
public void sleep() {
System.out.println("ao ao shui");
}
- 秘书类
public void laiBeiJiu(){
System.out.println("laiBeiJiu");
}
public void laiGenYan(){
System.out.println("laiGenYan");
}