首页 > 其他分享 >声明式事务操作-完全注解方式

声明式事务操作-完全注解方式

时间:2023-02-23 22:59:53浏览次数:27  
标签:事务 org springframework dataSource context import 注解 声明 public

1.创建配置类

package spring.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan(basePackages = {"spring"})//组件扫描
@EnableTransactionManagement//开启事务
public class MyConfig {

    //创建数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/yeb?serverTimezone=Asia/Shanghai");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    //创建jdbcTemplate对象
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        //到ioc容器中根据类型找到dataSource
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //注入dataSource
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //创建事务管理器
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}

 

 

 

 

2.测试代码

 @Test
    public void test5(){
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        AccountService accountService = context.getBean("accountService", AccountService.class);
        accountService.transfer();
    }

 

标签:事务,org,springframework,dataSource,context,import,注解,声明,public
From: https://www.cnblogs.com/ixtao/p/17149748.html

相关文章