基于spring的开启声明式事物全注解实现的方式(单spring项目)

package com.ricardo.spring5.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;

/**
 * @author ldy
 * @date 2020-12-29 11:22
 **/
@Configuration
@ComponentScan("com.ricardo.spring5")
@EnableTransactionManagement
public class TxConfig {

    // 数据源
    @Bean
    public DruidDataSource getDruidDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/spring5");
        druidDataSource.setPassword("root");
        druidDataSource.setUsername("liudieyi1206@");
        return druidDataSource;
    }

    // JdbcTemplate对象
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

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

代码借鉴B站尚硅谷-Spring5框架2020最新版教程(idea版)
尚硅谷-Spring5框架2020最新版教程(idea版)

你可能感兴趣的:(Java,spring,java,mysql)