spring 手动 编程式事务 springmvc 事务 事务不起作用

1、你可能维护、编写一个老项目,老项目的作者对事务可能理解不够全面,在写事务的时候,认为它应该起作用,但是实际上它没起作用。一个例子:

配置了 spring 父applicationContext.xml,事务也在里面配置

配置了springMVC spring-mvc-config.xml

然后在controller里添加注解 @Transactional ,原作者认为该controller 里的那个方法会执行事务操作,但实际测试上线的时候,确没执行,但是你维护这个项目,有不敢随意改动原作者的code,因为可能是牵一发而动全身,但是你有得让它执行一系列的事务操作。(当然你可以让springMVC启动所有,不启动spring父类,这样就不用以下的改动,你也可以让spring父容器扫描controller,但依旧也不会起作用,或者你把事务配置挪到SpringMVC中,但一般不会这么做)。

2、实现

配置applicationContext.xml

添加配置:

<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">  
        <property name="transactionManager" ref="transactionManager"/>  
    </bean> 

使用:

可能是controller:

//注入

扫描二维码关注公众号,回复: 976337 查看本文章

@Autowired
    private TransactionTemplate transactionTemplate;

那个方法可能是这样:

//@RequestMapping("/pay")

//@Transactional
  public ModelAndView pay(arg1, arg2){

//业务逻辑

}

你再写个方法:

@RequestMapping("/pay")
  public ModelAndView payOrder(arg1, arg2){

//org.springframework.transaction.support.TransactionCallback

return transactionTemplate.execute(new TransactionCallback<ModelAndView>() {
            @Override
            public ModelAndView doInTransaction(TransactionStatus transactionStatus) {
                ModelAndView model = null;

                //若有必要抓取异常,一定要throw给模板,否则事务不起作用
                try {
                    model = pay(arg1, arg2);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return model;
            }
        });

}

如果方法没有返回值 你继承org.springframework.transaction.supportTransactionCallbackWithoutResult,替换上面的那个TransactionCallback<T>

3、剩下的你自己调,希望有需要的朋友拿走

猜你喜欢

转载自my.oschina.net/u/1434882/blog/1787606