0%

解决调用Spring注解式事务方法不生效的问题

看如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Component
public class FooServiceImpl implements FooService {
@Autowired
private JdbcTemplate jdbcTemplate;

@Override
@Transactional(rollbackFor = RollbackException.class)
public void insertThenRollback() throws RollbackException {
jdbcTemplate.execute("INSERT INTO FOO (BAR) VALUES ('BBB')");
throw new RollbackException();
}

@Override
public void invokeInsertThenRollback() throws RollbackException {
insertThenRollback();
}
}

方法 invokeInsertThenRollback() 调用一个有 @Transactional 注释的方法,这时,事务未生效。

有两种方法可以解决。

方法一,把自身 FooService 注入进来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Component
public class FooServiceImpl implements FooService {
@Autowired
private JdbcTemplate jdbcTemplate;

@Autowired
private FooService fooService;

@Override
@Transactional(rollbackFor = RollbackException.class)
public void insertThenRollback() throws RollbackException {
jdbcTemplate.execute("INSERT INTO FOO (BAR) VALUES ('BBB')");
throw new RollbackException();
}

@Override
public void invokeInsertThenRollback() throws RollbackException {
// insertThenRollback();
fooService.insertThenRollback();
}
}

方法二,调用 AopContext.currentProxy() 获取代理类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Component
public class FooServiceImpl implements FooService {
@Autowired
private JdbcTemplate jdbcTemplate;

@Override
@Transactional(rollbackFor = RollbackException.class)
public void insertThenRollback() throws RollbackException {
jdbcTemplate.execute("INSERT INTO FOO (BAR) VALUES ('BBB')");
throw new RollbackException();
}

@Override
public void invokeInsertThenRollback() throws RollbackException {
// insertThenRollback();
((FooService) (AopContext.currentProxy())).invokeInsertThenRollback();
}
}