学习Spring事务操作-优化

This commit is contained in:
2026-10-16 10:20:48 +08:00
parent 00a7d3777d
commit 2cf5c791f9
2 changed files with 17 additions and 5 deletions
@@ -1,8 +1,10 @@
package com.ycjy.config;
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.jdbc.datasource.DriverManagerDataSource;
@@ -13,6 +15,7 @@ import javax.sql.DataSource;
@Configuration
@ComponentScan("com")
@PropertySource("classpath:db.p")
@EnableTransactionManagement // 启用事务管理
public class Application {
@Bean
@@ -21,12 +24,17 @@ public class Application {
}
@Bean
public DataSource dataSource(){
public DataSource dataSource(
@Value("${jdbc.driverClassName}") String driverClassName,
@Value("${jdbc.url}") String url,
@Value("${jdbc.username}") String username,
@Value("${jdbc.password}") String password
){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root");
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@@ -0,0 +1,4 @@
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root