Skip to content

Instantly share code, notes, and snippets.

@xcaspar
Created July 20, 2015 09:24
Show Gist options
  • Save xcaspar/d96e772175bd64132e23 to your computer and use it in GitHub Desktop.
Save xcaspar/d96e772175bd64132e23 to your computer and use it in GitHub Desktop.

Spring事务自身调用

####场景 对象调用自身具有事务传播的方法,同时使事务有效。 ####解决方法 使用AopContext.currentProxy()获取此类的AOP代理对象,用代理对象调用自身方法。注意,使用此解决方式,在spring配置文件的aop配置要添加expose-proxy="true"。 ####代码实现 Spring相关配置:<aop:aspectj-autoproxy proxy-target- expose-proxy="true"/> ####业务代码 在deliverItemAsyncCallback方法中调用deliverCallBackBusiness方法,并且使其事务有效。

@Componentpublic 
class TradeDeliverCallbackBusiness {
    @Transactional(propagation = Propagation.REQUIRED)
    public OrderResult deliverItemAsyncCallback(final String orderSn) {
        // ....
        // 获取代理类,调用具有事务的自身方法
        OrderResult orderResult = ((TradeDeliverCallbackBusiness)AopContext.currentProxy()).deliverCallBackBusiness(orderSn);
        // ...
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public OrderResult deliverCallBackBusiness(final String orderSn) {
        // ...
    }
}

####注意事项 1. 方法必须是public。 2. 调用事务的方法本身要有AOP功能,比如deliverItemAsyncCallback方法。 3. Spring配置中要将expose-proxy置为true。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment