1 ProxyFactory类分析
前言:在AOP增强的Bean,是在Bean的后置处理器我们跟到AbstractAutoProxyCreator的createProxy方法。(飞机票 https://blog.csdn.net/qq_34125999/article/details/104572875 详细的介绍了AOP和AOP加强类)
AOP的代理工厂,此类提供了一种在自定义用户代码中获取和配置AOP代理实例的简单方法
(1) setTarget,创建一个单例的代理对象
/**
* Set the given object as target.
* Will create a SingletonTargetSource for the object.
* @see #setTargetSource
* @see org.springframework.aop.target.SingletonTargetSource
*/
public void setTarget(Object target) {
setTargetSource(new SingletonTargetSource(target));
}
(2) addAdvice添加代理方法,该方法实现了Advice接口
@Override
public void addAdvice(Advice advice) throws AopConfigException {
int pos = this.advisors.size();
addAdvice(pos, advice);
}
(3) getProxy() 获取代理对象,AOP代理的Bean是通过该方法增强的
//创建AOP代理对象并且得到对象
public Object getProxy() {
return createAopProxy().getProxy();
}
2 MethodInterceptor类,实现了通知接口和拦截接口,用于类的加强
3 demo
(1) TeacherService
@Service
public class TeacherService {
public void addTeacher(){
System.out.println("add teacher");
}
}
(2) TeacherMethodInterceptor ,创建方法拦截器如果方法名等于addTeacher时那么增强方法。(在Bean初始化时,AOP会拿到切面类,判断该类是否被加强,如果被加强获取到加强的方法)
public class TeacherMethodInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object proxy=null;
// 方法名
String methodName = invocation.getMethod().getName();
//如果方法名等于
if (methodName.equals("addTeacher")){
System.out.println("addTeacher.........before");
proxy = invocation.proceed();
System.out.println("addTeacher.........after");
}
return proxy;
}
}
(3) 测试
public class SpringApplicationContext {
public static void main(String[] args) {
//1 创建代理工厂
ProxyFactory proxyFactory = new ProxyFactory();
//2 设置代理目标
proxyFactory.setTarget(new TeacherService());
//3 设置增强方法
proxyFactory.addAdvice(new TeacherMethodInterceptor());
//4 获取代理对象
TeacherService proxy = (TeacherService) proxyFactory.getProxy();
//5 执行方法
proxy.addTeacher();
}
}
4 AOP方法链
(1) 打断点debug,发现calculatorService已经被CglibAopProxy代理
(2) CglibAopProxy intercept方法拦截
(3) ReflectiveMethodInvocation. proceed()方法调用
方法调用实现类:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/15155.html