/**
* @author 11412
* @date 2023/07/14
**/
//全注解是真牛逼嗨
@Configuration
@ComponentScan("com.sdws.spring6")
@EnableTransactionManagement
public class SpringConfig {
//连接数据库
@Bean
public DataSource getDatasource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/spring");
dataSource.setPassword("root");
dataSource.setUsername("root");
return dataSource;
}
//创建JdbcTemplate
@Bean()
public JdbcTemplate getJdbcTemplate(DataSource dataSource){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
//开启事务
@Bean
public DataSourceTransactionManager getDataSourceTransactionManger(DataSource dataSource){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}
如果已经在xml文件中配置过的话要注意冲突问题。
导入方式
/**
* @author 11412
* @date 2023/07/14
**/
public class TxByAllAnnotationTest {
@Test
public void textTxByAllAnnotationTest(){
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
BookController bookController = context.getBean("bookController", BookController.class);
Integer[] bookIDS={1,2};
bookController.checkOut(bookIDS,1);
}
}