Spring框架学习[AOP通知以及编程式AOP ](十)

2014-11-24 03:05:50 · 作者: · 浏览: 6
ew Object[] {mi.getMethod(), mi.getArguments(), mi.getThis(), ex}; } try { //使用JDK反射机制,调用异常通知的异常处理方法 method.invoke(this.throwsAdvice, handlerArgs); } catch (InvocationTargetException targetEx) { throw targetEx.getTargetException(); } }}

6.ProxyFactory实现编程式AOP:

在上一篇博客《创建AOP代理对象并对目标对象切面拦截》中,我们以ProxyFactoryBean 为例,分析了Spring创建AOP代理对象以及对目标对象进行切面拦截的实现过程,在Spring中还有另一个创建AOP代理对象的容器——ProxyFactory,两个创建AOP代理对象容器的区别如下:

a.ProxyFactory:创建编程式的Spring AOP应用。

b.ProxyFactoryBean:创建声明式的Spring AOP应用。

我们现在通过分析ProxyFactory源码,了解Spring编程式AOP应用的具体实现:

(1).使用ProxyFactory编程式AOP应用的简单例子:

[java] view plaincopyprint //获取目标对象 TargetImpl target = new TargetImpl(); //创建目标对象的代理工厂 ProxyFactory aopFactory = new ProxyFactory(target); //为目标对象代理工厂添加通知器 aopFactory.addAdvisor(要添加的Advisor); //为目标对象代理工厂添加通知 aopFactory.addAdvice(要添加的Advice); //获取目标对象的代理 TargetImpl targetProxy = (TargetImpl)aopFactory.getProxy();

(2).ProxyFactory源码:

[java] view plaincopyprint public class ProxyFactory extends ProxyCreatorSupport { //创建一个空的AOP代理容器 public ProxyFactory() { } //为目标对象创建AOP代理容器 public ProxyFactory(Object target) { Assert.notNull(target, "Target object must not be null"); setInterfaces(ClassUtils.getAllInterfaces(target)); setTarget(target); } //根据代理接口创建AOP代理容器 public ProxyFactory(Class[] proxyInterfaces) { setInterfaces(proxyInterfaces); } //为指定代理接口和拦截器创建AOP代理容器 public ProxyFactory(Class proxyInterface, Interceptor interceptor) { //为代理对象添加代理接口 addInterface(proxyInterface); //为代理对象添加拦截器 addAdvice(interceptor); } //根据指定目标源和代理接口创建代理容器 public ProxyFactory(Class proxyInterface, TargetSource targetSource) { addInterface(proxyInterface); //为通知设置目标源 setTargetSource(targetSource); } //获取AOP代理 public Object getProxy() { return createAopProxy().getProxy(); } //使用指定类加载器创建AOP代理 public Object getProxy(ClassLoader classLoader) { return createAopProxy().getProxy(classLoader); } //获取指定代理接口和拦截器的AOP代理 public static T getProxy(Class proxyInterface, Interceptor interceptor) { return (T) new ProxyFactory(proxyInterface, interceptor).getProxy(); } //获取指定代理接口和目标源的AOP代理 public static T getProxy(Class proxyInterface, TargetSource targetSource) { return (T) new ProxyFactory(proxyInterface, targetSource).getProxy(); } //为指定目标源创建AOP代理 public static Object getProxy(TargetSource targetSource) { if (targetSource.getTargetClass() == null) { throw new IllegalArgumentException("Cannot create class proxy for TargetSource with null target class"); } ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTargetSource(targetSource); proxyFactory.setProxyTargetClass(true); return proxyFactory.getProxy(); } }