1. 程式人生 > >註解驅動開發四純註解實現宣告式事務(無xml)

註解驅動開發四純註解實現宣告式事務(無xml)

配置類如下:

@EnableTransactionManagement
@ComponentScan("com.web.tx")
@Configuration
public class TxConfig {
	
	//資料來源
	@Bean
	public DataSource dataSource() throws Exception{
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		dataSource.setUser("root");
		dataSource.setPassword("123456");
		dataSource.setDriverClass("com.mysql.jdbc.Driver");
		dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
		return dataSource;
	}
	
	//
	@Bean
	public JdbcTemplate jdbcTemplate() throws Exception{
		//Spring對@Configuration類會特殊處理;給容器中加元件的方法,多次呼叫都只是從容器中找元件
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource());
		return jdbcTemplate;
	}
	
	//註冊事務管理器在容器中
	@Bean
	public PlatformTransactionManager transactionManager() throws Exception{
		return new DataSourceTransactionManager(dataSource());
	}
}

@EnableTransactionManagement註解功能:開啟基於註解的事務管理功能。

等同於以前xml配置:

<tx:annotation-driven/>

另外需要注意註冊事務管理器bean於Spring容器中。

UserDao如下:

@Repository
public class UserDao {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	public void insert(){
		String sql = "INSERT INTO `tbl_user`(username,age) VALUES(?,?)";
		String username = UUID.randomUUID().toString().substring(0, 5);
		jdbcTemplate.update(sql, username,19);
	}

}

UserService如下:

@Service
public class UserService2 {
	
	@Autowired
	private UserDao userDao;
	
	@Transactional
	public void insertUser(){
		userDao.insert();
		//otherDao.other();xxx
		System.out.println("插入完成...");
		int i = 10/0;//這裡人為丟擲異常,測試事務
	}

}

測試類如下:

public class IOCTest_Tx {
	
	@Test
	public void test01(){
		AnnotationConfigApplicationContext applicationContext = 
				new AnnotationConfigApplicationContext(TxConfig.class);
	
		UserService2 userService = applicationContext.getBean(UserService2.class);
		
		userService.insertUser();
		applicationContext.close();
	}

}

綜上,可以看到將資料來源,事務管理器等以前xml配置的方式替換為註解形式,可以實現完全無xml的宣告式事務。