配置文件信息
/** * @EnableTransactionManagement 开启基于注解的事务管理功能 * 1、配置数据源 * 2、配置事务管理器来管理事务 * 3、给方法上标注 @Transactional 表示当前方法是一个事务方法 */ @EnableTransactionManagement @Configuration public class TxConfig { @Bean public DataSource dataSource() throws PropertyVetoException { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setUser("yang"); dataSource.setPassword("yang"); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test"); return dataSource; } /** * 如果bean之间有依赖,直接放进参数中即可,参数值会从Spring容器中取,然后赋值 * 参数从Spring容器中取 * * @param dataSource * @return */ @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // 也可以直接调用,Spring对@Configuration类会特殊处理;给容器中加组件的方法,多次调用都只是从容器中找组件 // JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource()); return jdbcTemplate; } /** * 注册事务管理器在容器中 * * @return * @throws Exception */ @Bean public PlatformTransactionManager transactionManager() throws Exception { return new DataSourceTransactionManager(dataSource()); } }
@EnableTransactionManagement 做了什么?
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(TransactionManagementConfigurationSelector.class) public @interface EnableTransactionManagement { boolean proxyTargetClass() default false; AdviceMode mode() default AdviceMode.PROXY; int order() default Ordered.LOWEST_PRECEDENCE; }
1、导入了TransactionManagementConfigurationSelector,TransactionManagementConfigurationSelector往容器中导入了两个组件
return new String[] {AutoProxyRegistrar.class.getName(), ProxyTransactionManagementConfiguration.class.getName()};
AutoProxyRegistrar和ProxyTransactionManagementConfiguration
2、AutoProxyRegistrar
给容器中注册了一个beanNameorg.springframework.aop.config.internalAutoProxyCreator,类型为InfrastructureAdvisorAutoProxyCreator
的组件(bean),其是一个后置处理器,和AOP中的AnnotationAwareAspectJAutoProxyCreator类似,它们beanName相同。
都是在对象创建完成之后利用后置处理器的初始化后置方法,包装对象,然后返回一个包含增强器的代理对象,代理对象执行方法利用拦截器链进行调用。
3、ProxyTransactionManagementConfiguration是一个配置文件类
往容器中