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;
//@Configuration是指代替xml配置
//@ComponentScan配置扫描路径
//@EnableTransactionManagement开启事务管理
@Configuration
@ComponentScan(basePackages = {"com.demo"})
@EnableTransactionManagement
public class SpringConfig {
//创建数据库连接池
@Bean
public DruidDataSource getDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
//创建JDBC模板
@Bean
public JdbcTemplate getJdbcTemplate (DruidDataSource dataSource){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
//创建事务管理器
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager (DruidDataSource dataSource){
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
Spring完全注解开发配置模板
最新推荐文章于 2022-06-16 20:57:31 发布