spring声明事务失效问题(二)

上次谈到spring的aop无法拦截内部方法调用时,解决方案之一是重新获取代理类调用B方法。

下面说一下如何获取到代理bean。

1、如果知道beanName直接通过上下文获取到bean。

2、如果不知道beanName,则可以放在线程变量中,如下:

     在action中调用时可以先调用spring提供的接口AopContext.setCurrentProxy(proxy)。

     该接口原理就是将代理bean放到线程变量中

public abstract class AopContext {
	private static final ThreadLocal<Object> currentProxy = new NamedThreadLocal<Object>("Current AOP proxy");

	public static Object currentProxy() throws IllegalStateException {
		Object proxy = currentProxy.get();
		if (proxy == null) {
			throw new IllegalStateException(
					"Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.");
		}
		return proxy;
	}

	static Object setCurrentProxy(Object proxy) {
		Object old = currentProxy.get();
		if (proxy != null) {
			currentProxy.set(proxy);
		}
		else {
			currentProxy.remove();
		}
		return old;
	}

}

  当需要调用时,则调用接口((BeanClass) AopContext.currentProxy()).B();

  如果在配置中将expose-proxy设置为true,则直接获取就可以了:

<aop:config expose-proxy="true"><!—xml风格支持-->  

猜你喜欢

转载自lipengjavablog.iteye.com/blog/2201981