全注解实现事务管理,就是取消 spring-config.xml 文件,而将配置信息在配置类中实现。
配置类:
package com.spring.book;
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.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan(value = "com.spring.book")
@EnableTransactionManagement
public class SpringConfig {
@Bean
public DruidDataSource getDruidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUrl("jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false");
druidDataSource.setUsername("root");
druidDataSource.setPassword("374296");
return druidDataSource;
}
@Bean
public JdbcTemplate getJdbcTemplate() {
return new JdbcTemplate(getDruidDataSource());
}
@Bean
public TransactionManager getTransactionManager() {
return new DataSourceTransactionManager(getDruidDataSource());
}
}
测试类:
import com.spring.book.BookController;
import com.spring.book.SpringConfig;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TxByAnnotationTest {
@Test
public void testBuyBook() throws InterruptedException {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
BookController bookController = context.getBean("bookController", BookController.class);
bookController.buyBook(1,1);
}
}