20_Spring_零XML事务控制

20_Spring_零XML事务控制

创建配置类

  1. package com.msb.config;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.ComponentScan;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.context.annotation.PropertySource;
  8. import org.springframework.jdbc.core.JdbcTemplate;
  9. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  10. import org.springframework.transaction.PlatformTransactionManager;
  11. import
    org.springframework.transaction.annotation.EnableTransactionManagement;
  12. import javax.sql.DataSource;
  13. /**
    • @Author: Ma HaiYang
    • @Description: MircoMessage:Mark_7001
  14. */
  15. @Configuration // 配置类标志注解
  16. @ComponentScan(basePackages = "com.msb") // spring包扫描
  17. @PropertySource("classpath:jdbc.properties") // 读取属性配置文件
  18. @EnableTransactionManagement // 开启事务注解
  19. public class SpringConfig {
  20. @Value("${jdbc_driver}")
  21. private String driver;
  22. @Value("${jdbc_url}")
  23. private String url;
  24. @Value("${jdbc_username}")
  25. private String username;
  26. @Value("${jdbc_password}")
  27. private String password;
  28. /创建数据库连接池/
  29. @Bean
  30. public DruidDataSource getDruidDataSource(){
  31. DruidDataSource dataSource=new DruidDataSource();
  32. dataSource.setDriverClassName(driver);
  33. dataSource.setUrl(url);
  34. dataSource.setUsername(username);
  35. dataSource.setPassword(password);
  36. return dataSource;
  37. }
  38. /创建JdbcTemplate对象/
  39. @Bean
  40. public JdbcTemplate getJdbcTemplate(DataSource dataSource){
  41. JdbcTemplate jdbcTemplate=new JdbcTemplate();
  42. jdbcTemplate.setDataSource(dataSource);
  43. return jdbcTemplate;
  44. }
  45. /创建事务管理器/
  46. @Bean
  47. public PlatformTransactionManager
    getPlatformTransactionManager(DataSource dataSource){
  48. DataSourceTransactionManager transactionManager =new
    DataSourceTransactionManager();
  49. transactionManager.setDataSource(dataSource);
  50. return transactionManager;
  51. }
  52. }

测试代码

  1. @Test()
  2. public void testTransaction3(){
  3. ApplicationContext context =new
    AnnotationConfigApplicationContext(SpringConfig.class);
  4. AccountService accountService =
    context.getBean(AccountService.class);
  5. int rows = accountService.transMoney(1, 2, 100);
  6. System.out.println(rows);
  7. }

posted @ 2023-07-30 12:42  AidenDong  阅读(25)  评论(0)    收藏  举报