@component public class FooServiceImpl implements FooService{ @Autowired private JdbcTemplate jdbcTemplate; @Override @Transactional public void insertRecord(){ jdbcTempalte.eccute("INSERT INTO FOO (BAR) VALUES('AAA')"); } @Overrive @Transactional(rollbackFor = RollbackException.calss) public void insertThenRollback(){ jdbcTemplate.excute("INSERT INTO FOO (BAR) VALUES ('BBB')"); throw new RollbackException(); } @Overrive public void invokeInsertThenRollback() throws RollbackException{ insertThenRollback(); } //要想上面这个方法添加上事务 第一步:注入实例 @Autowired private FooService fooService; //把自己的实例注入进来,比较方便理解 @Override public void invokeInsertThenRollbackBySelfService() throws RollbackException { fooService.insertThenRollback(); } //获取当前代理,这样写避免了自己调用自己的实例 @Override public void invokeInsertThenRollbackByAopContext() throws RollbackException { ((FooService) (AopContext.currentProxy())).insertThenRollback(); } //再加一层事务 @Transactional(rollbackFor = RollbackException.class) @Override public void invokeInsertThenRollbackAddTransactional() throws RollbackException { insertThenRollback(); } } Public class DeclarativeTransactionDemApplication implements CommandLineRunner{ @Autowried private FooService fooService; @Autowried private JdbcTemplate jdbcTemplate; public static void main (String[] args){ SpringApplication.run(DeclarativeTransactionDemApplication.class); } @Override public void run(String... args){ fooSerive.insertRecord(); log.info("AAA {}",jdbcTemplate.queryForObject("SELECT COUNT(*) FROM FOO WHERE BAR ='AAA'",Long.class)); //结果 1 try{ fooService.insertThenRollback(); }catch(Exception e){ log.info("BBB {}",jdbcTemplate.queryForObject("SELECT COUNT(*) FROM FOO WHERE BAR ='BBB'",Long.class)); } //结果 0 try{ fooService.invokeInsertThenRollback(); }catch(Exception e){ log.info("BBB {}",jdbcTemplate.queryForObject("SELECT COUNT(*) FROM FOO WHERE BAR ='BBB'",Long.class)); } //结果 1 spring 事务是通过穿建 代理对象来添加事务 这个是内部调用 调用方法 所以在调用的时候不会增强事务 //要想它加上事务 } }