在service中有兩個方法 A和 B,
A沒有配置事務,B配事務,
若在A中調用B方法時,事務將不起作用,原因是因爲spring的事務是基於AOP的方式,是代理類加的增強,Proxy.B,若在內部調用時則僅是直接調用B,事務將失效。
解決方法:1 將B移到另一個類中
2 A調用B時不直接調用B,而是調用AOP代理類 的B方法
可以在A實現類中聲明A接口 然後加載時將代理類賦給它。
- @Service
- public class InjectBeanSelfProcessor implements BeanPostProcessor , ApplicationContextAware {
- private ApplicationContext context;
- //① 注入ApplicationContext
- public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
- this.context = applicationContext;
- }
- public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
- if (bean instanceof BeanSelfAware) {
- if (AopUtils.isAopProxy(bean)) {
- LogConstant.debugLog.info("[postProcessAfterInitialization][isAopProxy][beanName = "+beanName+"][className= "+bean.getClass()+"]" );
- ((BeanSelfAware) bean).setSelf(bean);
- } else {
- ((BeanSelfAware) bean).setSelf(context.getBean(beanName));
- LogConstant.debugLog.info("[postProcessAfterInitialization][isNotAopProxy][beanName = "+beanName+"][className= "+bean.getClass()+"]" );
- }
- }
- return bean;
- }
- public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
- return bean;
- }
- }
3. 通過Threadlocal暴漏AOP代理對象,
3.1.配置
- <aop:aspectj-autoproxy expose-proxy="true"/><!—註解風格支持-->
3.2在A方法中AopContext.currentProxy()).b();
調用B方法
參考博客:http://jinnianshilongnian.iteye.com/blog/1487235
http://jinnianshilongnian.iteye.com/blog/1492424