在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