Spring-tx-@EnableTransactionManagement注解

xml形式的spring配置使用tx标签来开启事务
而注解形式的spring配置,则使用@EnableTransactionManagement注解

其实本文要说的内容,在该注解的注释当中都有,例如下面这个代码

@Component
public class Creater1 {
    
    

	@Autowired
	JdbcTemplate jdbcTemplate;

	@Transactional(rollbackFor = Exception.class)
	public void create() {
    
    
		jdbcTemplate.update("insert into t1(value) values ('HAHA')");
		throw new RuntimeException("抛异常就回滚");
	}
}
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.zaxxer.hikari.HikariDataSource;

@Configuration
@EnableTransactionManagement
public class TestMain {
    
    

	@Bean
	public DataSource dataSource() {
    
    
		HikariDataSource ds = new HikariDataSource();
		ds.setJdbcUrl("jdbc:mysql://localhost:3306/swttest?serverTimezone=UTC&&useSSL=false");
		ds.setUsername("root");
		ds.setPassword("123456");
		return ds;
	}

	@Bean
	public JdbcTemplate jdbcTemplate() {
    
    
		JdbcTemplate jdbc = new JdbcTemplate();
		jdbc.setDataSource(dataSource());
		return jdbc;
	}

	@Bean
	public PlatformTransactionManager platformTransactionManager() {
    
    
		return new DataSourceTransactionManager(dataSource());
	}

	public static void main(String[] args) throws Throwable {
    
    
		// 依赖容器的话必须要开启@EnableTransactionManagement注解,表示告诉spring我要使用事务
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
				"com.example.studyintegration.spring.Transcation.TranscationStatus");
		Creater1 tt = ctx.getBean(Creater1.class);
		tt.create();
	}
}

上面就是使用该注解的方式,开启事务,抛异常就会回滚,需要注意的地方:
@EnableTransactionManagement注解必须配合@Configuration注解使用,否则不会生效事务功能

日记:@Configuration注解等同于java版本的xml文件,以前xml版本的tx标签是写到xml文件中的,而EnableTransactionManagement等同于tx标签,这也更加印证了Configuration注解就是一个java抽象的xml文件

在@Configuration的注释中其中就说明了这一项

Enabling built-in Spring features using @Enable annotations
Spring features such as asynchronous method execution, 
scheduled task execution,
annotation driven transaction management, 
and even Spring MVC can be enabled andconfigured from @Configuration classes using their respective "@Enable"annotations. 
See @EnableAsync, 
@EnableScheduling, 
@EnableTransactionManagement,
@EnableAspectJAutoProxy,
and @EnableWebMvcfor details.

猜你喜欢

转载自blog.csdn.net/u011624903/article/details/112615136