Spring中的aop
今天介绍一下Spring aop技术,即面向切面的技术,不知道为什么,听着就觉得很牛逼。
一、什么是aop:
二、为什么学习 AOP
对程序进行增强:不修改源码的情况下.
AOP 可以进行权限校验,日志记录,性能监控,事务控制
三、Spring 的 AOP 的由来:
AOP 最早由 AOP 联盟的组织提出的,制定了一套规范.Spring 将 AOP 思想引入到框架中,必须遵守 AOP 联盟规范
四、底层实现
动态代理机制:
Spring 的 AOP 的底层用到两种代理机制:
- JDK 的动态代理 :针对实现了接口的类产生代理. 具体可见我另一篇博客:https://blog.csdn.net/lx678111/article/details/82818634
- Cglib 的动态代理 :针对没有实现接口的类产生代理. 应用的是底层的字节码增强的技术 生成当前类的子类对象
cglib
实现MethodInterceptor接口,
Enhancer en=new Enhancer();//帮我们生成代理对,cglib核心类
en.setSuperclass(UserServiceImpl.class);//设置对谁进行代理
en.setCallback(this);//代理要做什么
实现intercept(...)方法
methodProxy.invokeSuper(proxyObj, args);//放行
总结一点:动态代理即面向接口,cglib即生成当前类的代理子对象
package cn.hncu.proxy;
import java.lang.reflect.Method;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import cn.hncu.service.UserService;
import cn.hncu.service.UserServiceImpl;
public class UserServiceProxyFactory2 implements MethodInterceptor{
public UserService getUserServiceProxy() {
Enhancer en=new Enhancer();//帮我们生成代理对象
en.setSuperclass(UserServiceImpl.class);//设置对谁进行代理
en.setCallback(this);//代理要做什么
UserService us = (UserService) en.create();
return us;
}
@Override
public Object intercept(Object proxyObj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
//打开事务
System.out.println("打开事务!");
//调用方法
Object returnValue =methodProxy.invokeSuper(proxyObj, args);
//在方法之后提交事务
System.out.println("提交事务!");
return returnValue;
}
}
五、Spring中的aop原理
六、Spting aop专业术语
joinpoint连接点:目标对象中,所有可以增强的方法
pointcut切入点:目标对象,以及增强的方法
advice通知/增强: 增强的代码
target目标对象:被代理的对象
weaving织入:将通知应用到切入点的过程
proxy代理:将通知织入到目标对象之后,形成代理对象
AOP中的一个重要等式:
- 切面(aspeect)=切点+通知
- advisor=cutpoint+advice
- 切面: 定义的一个拦截事件(动作)
- 切点: 要拦截哪些(个)类的哪些(个)方法
- 通知: 定义在方法的前面、后面、环绕、出异常 还是 正常返回的时候拦