Spring Boot的事务处理
spring boot大大简化了之前java项目需要在配置xml里设置很多繁琐的内容。
设置数据源和配置事务
@Bean(name = "masterDataSource")
@Primary
public DataSource druidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
druidDataSource.setInitialSize(initialSize);
druidDataSource.setMinIdle(minIdle);
druidDataSource.setMaxActive(maxActive);
druidDataSource.setMaxWait(maxWait);
druidDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
druidDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
druidDataSource.setValidationQuery(validationQuery);
druidDataSource.setTestWhileIdle(testWhileIdle);
druidDataSource.setTestOnBorrow(testOnBorrow);
druidDataSource.setTestOnReturn(testOnReturn);
druidDataSource.setPoolPreparedStatements(poolPreparedStatements);
druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
druidDataSource.setFilters("stat");
} catch (SQLException e) {
e.printStackTrace();
}
return druidDataSource;
}
@Bean(name = "masterTransactionManager")
@Primary
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(druidDataSource());
}
只需要在哪些需要事务的方法上面加上@Transactional(value="masterTransactionManager")就行