Spring中AOP设计思路是这样的.
在BeaFactory.getBean()时,调用方法initBean();
在该方法中判断当前Bean是否含有满足SpEL表达式的Method, 没有的话, 返回原始的Bean,
有的话, 会对当前Bean做动态代理,
当代理对象的方法被调用时,会发送通知到Aop拦截器,进而实现Aop的功能.
本篇文章思路接着上篇文章,
(手动模拟实现Spring-MVC)
https://blog.csdn.net/yangsnow_rain_wind/article/details/80223158
本次手动模拟Spring-Aop思路如下;
1.添加类FLAopProxy, 该类实现接口InvocationHandler, 用来实现Bean的动态代理功能
2.添加类FLAopConfig, 记录每个被代理Bean下所有满足条件的Method,并记录下其对应的aspject通知
3.修改类FLBeanWrapper
, 为该包装类添加新属性FLAopProxy
,用来记录Bean的代理配置
本次模拟类的包含关系如下图:
整个关系如下;
每个FLBeanWrapper
包含属性_originalBean(存储原始bean对象), _wrapperedBean(存储动态代理后的对象), FLAopProxy对象(用来生成动态代理).
每个FLAopProxy对象包含一个target属性, ()用来保存原始bean对象引用),包含一个FLAopConfig对象(保存Bean符合SpEl条件的method,及该method被调用时的aspect通知.)
下面是源码:
1. FLAopProxy
public class FLAopProxy implements InvocationHandler {
private FLAopConfig config = new FLAopConfig();
private Object target;
//对原始对象生成动态代理,
public Object getProxy(Object instance) {
this.target = instance;
Class<?> clazz = instance.getClass();
return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//当前的Method是代理后的method
Method originalMethod=this.target.getClass().getMethod(method.getName(),method.getParameterTypes());
//如果动态代理对象的方法属于config中配置的方法, 则调用前置通知
if (