Spring事务属性

事务相关配置

public interface Accountservice {
    @Transactional(readOnly = true, timeout = - 1)
    public void transfer(string out, string in, double money);
}

只有 Error 和运行时异常,会触发回滚

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    public void transfer(String out, String in, Double money) throws IOException {
        accountDao.outMoney(out, money);
        // int i = 1/10;
        if(true){ throw new IOException(); } // 不回滚
        accountDao.inMoney(in, money);
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;

    @Test
    public void testTransfer() throws IOException {
        accountService.transfer("Tom", "Jerry", 100D);
    }
}
public interface Accountservice {
    @Transactional(rollbackFor = {IOException.class)) // 对 IOException 回滚
    public void transfer(string out, string in, double money) throws IOException;
}

public interface LogService {
    @Transactional
    void log(String out, String in, Double money)
}
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private LogService logService;

    public void transfer(String out, String in, Double money) {
        try{
            accountDao.outMoney(out, money);
            int i = 1/0;
            accountDao.inMoney(in, money);
        }finally{
            logService.log(out, in, money);
        }
    }
}

日志记录同回滚

public interface LogService {
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    void log(String out, String in, Double money)
}

转账事务回滚,日志不回滚

事务传播行为

  • 事务传播行为:事务协调员对事务管理员所携带事务的处理态度