文章目录
面向切面编程AOP
1 Spring 的 AOP 简介
AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理
实现程序功能的统一维护的一种技术。
AOP 是 OOP 的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍
生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序
的可重用性,同时提高了开发的效率
1.2 AOP 的作用及其优势
作用:在程序运行期间,在不修改源码的情况下对方法进行功能增强
优势:减少重复代码,提高开发效率,并且便于维护
1.3 AOP 的底层实现
实际上, AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间, Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强
1.4 AOP 的动态代理技术
常用的动态代理技术
JDK 代理 : 基于接口的动态代理技术(通过实现目标相同接口增强方法)
cglib 代理:基于父类的动态代理技术 (通过继承目标重写增强方法)
JDK 代理
使用Proxy类创建代理对象
方法
- newProxyInstance()
参数:
- target.getClass().getClassLoader(),
- target.getClass().getInterfaces(),
- new InvocationHandler()
案例
被代理类
package com.raphuscucullatus.proxy.jdk;
public class Target implements TargetInterface {
@Override
public void save() {
System.out.println("save running.....");
}
}
被代理类的接口
package com.raphuscucullatus.proxy.jdk;
public interface TargetInterface {
public void save();
}
增强对象Advice
package com.raphuscucullatus.proxy.jdk;
public class Advice {
public void before(){
System.out.println("前置增强....");
public void afterReturning(){
System.out.println("后置增强....");
}
}
测试用例
package com.raphuscucullatus.proxy.jdk;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
//目标对象
Target target = new Target();
//增强对象
Advice advice = new Advice();
//返回值 就是动态生成的代理对象
TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//当被代理类方法名为save时,进行增强
if ("save".equals(method.getName())){
advice.before();
Object invoke = method.invoke(target);
advice.afterReturning();
return invoke;
}
return null;
}
}
);
//调用代理对象的方法
proxy.save();
}
}
cglib 代理
使用Enhancer类创建代理对象
方法
- enhancer.create();
设置参数:
-
enhancer.setSuperclass(Target.class);
-
enhancer.setCallback(new MethodInterceptor(){})
案例
被代理类 增强对象Advice 同上,不需要接口
测试用例
package com.raphuscucullatus.proxy.cglib;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class ProxyTest {
public static void main