@Transactional不适用于方法级别 [英] @Transactional does not work on method level

查看:208
本文介绍了@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?

推荐答案

你不能调用persist( )来自processDisclosureData(),因为它属于同一个类,它将绕过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天全站免登陆