20_Spring_零XML事务控制
20_Spring_零XML事务控制
创建配置类
- package com.msb.config;
- import com.alibaba.druid.pool.DruidDataSource;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.context.annotation.PropertySource;
- import org.springframework.jdbc.core.JdbcTemplate;
- import org.springframework.jdbc.datasource.DataSourceTransactionManager;
- import org.springframework.transaction.PlatformTransactionManager;
- import
org.springframework.transaction.annotation.EnableTransactionManagement; - import javax.sql.DataSource;
- /**
-
- @Author: Ma HaiYang
-
- @Description: MircoMessage:Mark_7001
- */
- @Configuration // 配置类标志注解
- @ComponentScan(basePackages = "com.msb") // spring包扫描
- @PropertySource("classpath:jdbc.properties") // 读取属性配置文件
- @EnableTransactionManagement // 开启事务注解
- public class SpringConfig {
-
@Value("${jdbc_driver}")
-
private String driver;
-
@Value("${jdbc_url}")
-
private String url;
-
@Value("${jdbc_username}")
-
private String username;
-
@Value("${jdbc_password}")
-
private String password;
-
/*创建数据库连接池*/
-
@Bean
-
public DruidDataSource getDruidDataSource(){
-
DruidDataSource dataSource=new DruidDataSource();
-
dataSource.setDriverClassName(driver);
-
dataSource.setUrl(url);
-
dataSource.setUsername(username);
-
dataSource.setPassword(password);
-
return dataSource;
-
}
-
/*创建JdbcTemplate对象*/
-
@Bean
-
public JdbcTemplate getJdbcTemplate(DataSource dataSource){
-
JdbcTemplate jdbcTemplate=new JdbcTemplate();
-
jdbcTemplate.setDataSource(dataSource);
-
return jdbcTemplate;
-
}
-
/*创建事务管理器*/
-
@Bean
-
getPlatformTransactionManager(DataSource dataSource){public PlatformTransactionManager
-
DataSourceTransactionManager();DataSourceTransactionManager transactionManager =new
-
transactionManager.setDataSource(dataSource);
-
return transactionManager;
-
}
- }
测试代码
- @Test()
-
public void testTransaction3(){
-
AnnotationConfigApplicationContext(SpringConfig.class);ApplicationContext context =new
-
context.getBean(AccountService.class);AccountService accountService =
-
int rows = accountService.transMoney(1, 2, 100);
-
System.out.println(rows);
-
}
标签:
spring
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理