spring 事务传播

在service中有两个方法 A和 B,

A没有配置事务,B配事务,

若在A中调用B方法时,事务将不起作用,原因是因为spring的事务是基于AOP的方式,是代理类加的增强,Proxy.B,若在内部调用时则仅是直接调用B,事务将失效。


解决方法:1 将B移到另一个类中

                 2 A调用B时不直接调用B,而是调用AOP代理类 的B方法

                  可以在A实现类中声明A接口 然后加载时将代理类赋给它。

              

           

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @Service  
  2. public class InjectBeanSelfProcessor implements BeanPostProcessor , ApplicationContextAware {  
  3.       
  4.      private ApplicationContext context;    
  5.         //① 注入ApplicationContext    
  6.         public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {    
  7.             this.context = applicationContext;    
  8.         }   
  9.       
  10.     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {  
  11.       
  12.         if (bean instanceof BeanSelfAware) {  
  13.             if (AopUtils.isAopProxy(bean)) {  
  14.                 LogConstant.debugLog.info("[postProcessAfterInitialization][isAopProxy][beanName = "+beanName+"][className= "+bean.getClass()+"]" );  
  15.                 ((BeanSelfAware) bean).setSelf(bean);  
  16.             } else {  
  17.                 ((BeanSelfAware) bean).setSelf(context.getBean(beanName));  
  18.                 LogConstant.debugLog.info("[postProcessAfterInitialization][isNotAopProxy][beanName = "+beanName+"][className= "+bean.getClass()+"]" );  
  19.             }  
  20.         }  
  21.         return bean;  
  22.     }  
  23.       
  24.     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {  
  25.       
  26.         return bean;  
  27.     }  
  28. }  


  3. 通过Threadlocal暴漏AOP代理对象,

     3.1.配置

  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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章