@Transactional 在方法级别不起作用 [英] @Transactional does not work on method level

查看:30
本文介绍了@Transactional 在方法级别不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 Spring 3.2.3 @Transactional 注释的问题.我的服务类看起来像这样:

I have a question about Spring 3.2.3 @Transactional annotation. My Service class looks like this:

@Service @Transactional
class InventoryDisclosureBO {

@Autowired InventoryDisclosureDAO inventoryDisclosureDAO;

private static final Logger log = LoggerFactory.getLogger( InventoryDisclosureBO.class);

public void processDisclosureData(InventoryDisclosureStatus data){
  validate(data);
  persist(data);
}

@Transactional(propagation = REQUIRES_NEW)
void persist(InventoryDisclosureStatus data) {
  inventoryDisclosureDAO.setAllInvalid( data.getUnit());
  inventoryDisclosureDAO.insert( data );
}

void validate(InventoryDisclosureStatus data) {
 ...
}
}

如果我调用 persist() 方法,一切都会完美运行.但是,如果我在类级别注释掉 @Transactional - 事务不会启动.有人能告诉我为什么 Spring 只能在甲醇级别忽略 @Transactional 吗?

All works perfectly if I call persist() method. But if I comment out @Transactional at class level - transaction does not start. Could anybody tell me why Spring could ignore @Transactional on methol-level only?

推荐答案

你不能从 processDisclosureData() 调用 persist() 因为它属于同一个类,它会绕过 Spring 为 InventoryDisclosureBO 创建的事务代理.您应该从其他 bean 调用它以使 @Transactional 注释工作.当 Spring 向其他 bean 注入对 InventoryDisclosureBO bean 的引用时,它实际上注入了对包含事务逻辑的 InventoryDisclosureBOProxy 的引用,例如

You cannot call persist() from processDisclosureData() because it belongs to the same class and it will bypass transactional proxy created by Spring for InventoryDisclosureBO. You should call it from other beans to make @Transactional annotations work. When Spring injects a reference to InventoryDisclosureBO bean to other beans it actually injects a reference to InventoryDisclosureBOProxy which contains transactional logic, eg

    class Bean2 {

      @Autowire
      private InventoryDisclosureBO idbo;   <-- Spring will inject a proxy here

      public void persist(InventoryDisclosureStatus data) {
           idbo.persist(data);     <-- now it will work via proxy
      }
...

这篇关于@Transactional 在方法级别不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆