JAVA

内部调用引起Spring声明式事务@Transactional失

2022-04-07  本文已影响0人  layasntx

失效的原因

Spring声明式事务是基于AOP生成的代理类来实现的,而AOP无法拦截内部调用,导致事务失效。

解决方案

  1. 将事务方法放到另一个类中,甚至可以创建一个“事务层”
  2. 获取代理对象,通过代理对象调用事务方法
  3. @Autowired 注入自身,通过注入的bean调用

总之都要修改原来的代码,那么能不能不改代码,答案是可以的。

简单分析一下 Spring AOP 源码

什么时候创建代理?

在AbstractAutoProxyCreator中的postProcessAfterInitialization中,这点很重要,我们需要在postProcessAfterInitialization之前,也就是初始化Bean之前修改内部调用方式

@Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
        Object cacheKey = getCacheKey(beanClass, beanName);
        // Create proxy here if we have a custom TargetSource.
        // Suppresses unnecessary default instantiation of the target bean:
        // The TargetSource will handle target instances in a custom fashion.
        TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
        if (targetSource != null) {
            if (StringUtils.hasLength(beanName)) {
                this.targetSourcedBeans.add(beanName);
            }
            Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
            Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
            this.proxyTypes.put(cacheKey, proxy.getClass());
            return proxy;
        }

        return null;
    }
创建代理

Srpring通过动态代理工厂DefaultAopProxyFactory创建代理, 有JDK和CGLIB两种实现方式。

public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
    @Override
    public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
            Class<?> targetClass = config.getTargetClass();
            if (targetClass == null) {
                throw new AopConfigException("TargetSource cannot determine target class: " +
                        "Either an interface or a target is required for proxy creation.");
            }
            //如果目标类是接口, 使用JDK动态代理来生成代理类及代理类实例对象
            if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
                return new JdkDynamicAopProxy(config);
            }
            //使用Cglib生成代理类及代理类实例对象
            return new ObjenesisCglibAopProxy(config);
        }
        else {
            return new JdkDynamicAopProxy(config);
        }
    }
}

我的解决方案

CGLIB的mathodproxy.invokesuper(proxy, args) 方法可以拦截内部调用,借助CGLIB,我们可以在Spring创建代理之前,对原本的代码进行增强。

TransactionalBeanProcessor
@Configuration
public class TransactionalBeanProcessor implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    /**
     * @param bean     源对象,此时还没有代理对象
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Method[] methods = bean.getClass().getMethods();
        for (Method method : methods) {
            // 对Transactional注解的方法进行增强
            if (method.isAnnotationPresent(Transactional.class) && !(bean instanceof TransactionalComponent)) {
                Enhancer enhancer = new Enhancer();
                //CGLIB增强基于继承,Superclass就是被代理的类
                enhancer.setSuperclass(bean.getClass());
                //代理逻辑放在Callback中
                enhancer.setCallback(new TransactionalMethodInterceptor(context));
                Object proxy = enhancer.create();
                //复制属性
                copyAction(proxy, bean);
                return proxy;
            }
        }
        return bean;
    }

    /**
     * @param bean     代理对象 AopProxy 
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    public void copyAction(Object target, Object origin) {
        Field[] targetFields = target.getClass().getSuperclass().getDeclaredFields();
        Class originClass = origin.getClass();
        Map<String, Field> originMap = convertObjectToMap(originClass);
        try {
            for (Field targetField : targetFields) {
                if (!Modifier.isFinal(targetField.getModifiers()) && originMap.containsKey(targetField.getName())) {
                    targetField.setAccessible(true);
                    Field originField = originMap.get(targetField.getName());
                    originField.setAccessible(true);
                    targetField.set(target, originField.get(origin));
                    targetField.setAccessible(false);
                    originField.setAccessible(false);
                }
            }
        } catch (Exception e) {
            return;
        }
    }

    public Map<String, Field> convertObjectToMap(Class originClass) {
        Map<String, Field> res = new HashMap<String, Field>();
        Field[] fields = originClass.getDeclaredFields();
        for (Field field : fields) {
            res.put(field.getName(), field);
        }
        return res;
    }
}
TransactionalMethodInterceptor
public class TransactionalMethodInterceptor implements MethodInterceptor {

    private ApplicationContext context;

    public TransactionalMethodInterceptor(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if (method.isAnnotationPresent(Transactional.class)) {
            final Object[] res = {null};
            //内部调用改为外部调用
            TransactionalUtils.required(context, () -> {
                res[0] = methodProxy.invokeSuper(o, objects);
            });
            return res[0];
        }
        return methodProxy.invokeSuper(o, objects);
    }
}
TransactionalComponent
@Component
public class TransactionalComponent {

    public interface Cell {
        void run() throws Throwable;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void required(Cell cell) throws Throwable {
        cell.run();
    }
}
TransactionalUtils
public class TransactionalUtils {

    private static volatile TransactionalComponent transactionalComponent;

    private static synchronized TransactionalComponent getTransactionalComponent(ApplicationContext context) {
        if (transactionalComponent == null) {
            // 从容器中获取 transactionalComponent
            transactionalComponent = context.getBean(TransactionalComponent.class);
        }
        return transactionalComponent;
    }

    public static void required(ApplicationContext context, TransactionalComponent.Cell cell) throws Throwable {
        getTransactionalComponent(context).required(cell);
    }
}

打完收工!!!

本文参考了以下博文,特此感谢:
https://blog.csdn.net/qq_28033719/article/details/108339751
https://baijiahao.baidu.com/s?id=1682843530518078672&wfr=spider&for=pc

上一篇下一篇

猜你喜欢

热点阅读