public class UserService{
@Autowired
private JdbcTemplate jdbcTemplate;
@Transactional
public void test(){
System.out.println("hello");
a();
}
// NEVER:以非事务方式执行,如果当前存在事务,则抛出异常
@Transactional(propagation = Propagation.NEVER)
public void a() {
jdbcTemplate.execute("insert t1 values (1,1,1,1,1)");
throw new NullPointerException();
}
}
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext = new ApplicationContext(AppConfig.class);
UserService userService = applicationContext.getBean("userService",UserService.class);
userService.test();
}
}
正常情况下,当test方法进入a方法时,此时存在事务,应该抛出异常,但实际上,并不会抛出异常。因为在Test类中,spring容器返回的对象userService,是经过AOP代理的对象。而真正调用test方法的对象是被代理对象,被代理对象调用的test方法,并没有事务,所以不会报错。
代理对象:
class UserServiceProxy extend UserService {
private UserService target;
public void test(){
// 1. 创建数据库连接conn
// 2. conn.autocommit = false;
target.test();
// 3. conn.commit();
}
}
如果想解决上述事务消除问题,解决方法,使用属性注入
public class UserService{
@Autowired
private JdbcTemplate jdbcTemplate;
// 在这里,userService由spring容器注入,spring容器注入的对象就是代理对象
@Autowired
private UserService userService;
@Transactional
public void test(){
System.out.println("hello");
userService.a(); // 此时使用代理对象调用a方法,代理对象存在事务,所以会出异常
}
// NEVER:以非事务方式执行,如果当前存在事务,则抛出异常
@Transactional(propagation = Propagation.NEVER)
public void a() {
jdbcTemplate.execute("insert t1 values (1,1,1,1,1)");
throw new NullPointerException();
}
}
同理,如果test方法无事务,给a方法加上事务,事务仍然无效,如下面这种情况,当代理对象执行test方法时,在执行a方法,调用的仍是被代理对象的a方法,仍然没有事务。
public class UserService{
@Autowired
private JdbcTemplate jdbcTemplate;
public void test(){
System.out.println("hello");
a();
}
@Transactional
public void a() {
jdbcTemplate.execute("insert t1 values (1,1,1,1,1)");
throw new NullPointerException();
}
}



