文章结构

  1. 源码阅读环境的搭建
  2. @EnableTransactionManagement注解的原理解析

    测试Demo

本篇文章的Demo基于上一篇文章SpringJDBC源码解析
新添加内容如下
首先在配置类中添加开启事务的注解@EnableTransactionManagement
然后添加DataSourceTransactionManagerBean

  1. @Beanpublic DataSourceTransactionManager
  2. dataSourceTransactionManager(DruidDataSource druidDataSource) {
  3. return new DataSourceTransactionManager(druidDataSource);
  4. }

在业务接口中新增一个抛出异常的修改方法

  1. public interface JDBCService {
  2. public void testTransactional();
  3. }
  4. @Transactional
  5. public class JDBCServiceImpl implements JDBCService {
  6. @Override
  7. public void testTransactional() {
  8. jdbcTemplate.update("update user set name='王五' where id=1", new Object[]{});
  9. throw new RuntimeException("异常");
  10. }
  11. }

启动Demo的类

  1. public class TransactionalDemo {
  2. public static void main (String args[]){
  3. ApplicationContext context = new AnnotationConfigApplicationContext("cn.shiyujun.config");
  4. JDBCService jdbcService= context.getBean(JDBCService.class);
  5. jdbcService.testTransactional();
  6. }
  7. }

至此Deno工程搭建完毕,有需要源码的同学可以从下方地址获取
https://github.com/shiyujun/spring-framework

源码解析

可以看到我们的事务是通过EnableTransactionManagement注解启用的,所以此次源码解析也从此注解开始

  1. @Target({ElementType.TYPE})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Import({TransactionManagementConfigurationSelector.class})
  5. public @interface EnableTransactionManagement {
  6. boolean proxyTargetClass() default false;
  7. AdviceMode mode() default AdviceMode.PROXY;
  8. int order() default 2147483647;
  9. }

相信看过我之前文章的同学都已经知道了@Import注解的原理了
Spring @Import注解源码解析 (见上文)
这里就不再详细解释了,直接看类TransactionManagementConfigurationSelector

  1. public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> {
  2. public TransactionManagementConfigurationSelector() {
  3. }
  4. protected String[] selectImports(AdviceMode adviceMode) {
  5. switch(adviceMode) {
  6. case PROXY:
  7. return new String[]{AutoProxyRegistrar.class.getName(), ProxyTransactionManagementConfiguration.class.getName()};
  8. case ASPECTJ:
  9. return new String[]{"org.springframework.transaction.aspectj.AspectJTransactionManagementConfiguration"};
  10. default:
  11. return null;
  12. }
  13. }
  14. }

可以看到这里是根据@EnableTransactionManagement注解的mode属性来确认注入哪一个配置类。这里由于我们没有指定属性,所以使用的默认的PROXY代理,走的是第一个分枝
所以在这里往Spring容器中注入了两个bean AutoProxyRegistrarProxyTransactionManagementConfiguration

创建自动代理的构建器

AutoProxyRegistrar类里面核心方法只有这一个

  1. public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
  2. boolean candidateFound = false;
  3. Set<String> annoTypes = importingClassMetadata.getAnnotationTypes();
  4. for (String annoType : annoTypes) {
  5. //获取注解元信息
  6. AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annoType);
  7. if (candidate == null) {
  8. continue;
  9. }
  10. Object mode = candidate.get("mode");
  11. Object proxyTargetClass = candidate.get("proxyTargetClass");
  12. if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() &&
  13. Boolean.class == proxyTargetClass.getClass()) {
  14. candidateFound = true;
  15. if (mode == AdviceMode.PROXY) {
  16. //由于咱们使用的默认PROXY所以走这个分支
  17. AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
  18. //强制使用Cglib动态代理
  19. if ((Boolean) proxyTargetClass) {
  20. AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
  21. return;
  22. }
  23. }
  24. }
  25. }
  26. if (!candidateFound) {
  27. String name = getClass().getSimpleName();
  28. logger.warn(String.format("%s was imported but no annotations were found " +
  29. "having both 'mode' and 'proxyTargetClass' attributes of type " +
  30. "AdviceMode and boolean respectively. This means that auto proxy " +
  31. "creator registration and configuration may not have occurred as " +
  32. "intended, and components may not be proxied as expected. Check to " +
  33. "ensure that %s has been @Import'ed on the same class where these " +
  34. "annotations are declared; otherwise remove the import of %s " +
  35. "altogether.", name, name, name));
  36. }
  37. }

往下看

  1. public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
  2. return registerAutoProxyCreatorIfNecessary(registry, (Object)null);
  3. }
  4. public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, @Nullable Object source) {
  5. return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
  6. }
  7. private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, Object source) {
  8. Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
  9. // 定义有AUTO_PROXY_CREATOR_BEAN_NAME="org.springframework.aop.config.internalAutoProxyCreator"
  10. if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
  11. // 如果容器中已经存在自动代理构建器,则比较两个构建器的优先级
  12. BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
  13. if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
  14. int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
  15. int requiredPriority = findPriorityForClass(cls);
  16. // 保存优先级高的构建器
  17. if (currentPriority < requiredPriority) {
  18. apcDefinition.setBeanClassName(cls.getName());
  19. }
  20. }
  21. return null;
  22. }
  23. // 如果容器中还没有自动代理构建器
  24. // 则创建构建器相应的BeanDefinition对象
  25. RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
  26. beanDefinition.setSource(source);
  27. beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
  28. beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
  29. // 向容器中注册代理构建器的BeanDefinition对象
  30. registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
  31. return beanDefinition;
  32. }

也就是说这一块的流程主要是为了注册org.springframework.aop.config.internalAutoProxyCreator这个bean

事务核心bean的构建

  1. public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
  2. @Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
  3. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  4. public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
  5. BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
  6. advisor.setTransactionAttributeSource(transactionAttributeSource());
  7. advisor.setAdvice(transactionInterceptor());
  8. if (this.enableTx != null) {
  9. advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
  10. }
  11. return advisor;
  12. }
  13. @Bean
  14. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  15. public TransactionAttributeSource transactionAttributeSource() {
  16. return new AnnotationTransactionAttributeSource();
  17. }
  18. @Bean
  19. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  20. public TransactionInterceptor transactionInterceptor() {
  21. TransactionInterceptor interceptor = new TransactionInterceptor();
  22. interceptor.setTransactionAttributeSource(transactionAttributeSource());
  23. if (this.txManager != null) {
  24. interceptor.setTransactionManager(this.txManager);
  25. }
  26. return interceptor;
  27. }
  28. }

进入这个类之后可以看到这个类是一个配置类,这个类一共注册了三个bean,不要小瞧这三个bean,就是它们三个完成了整个Spring的事务功能

再仔细看的话会发现,AnnotationTransactionAttributeSourceTransactionInterceptor这两个bea又都注册到了BeanFactoryTransactionAttributeSourceAdvisor中,可以看出来这里是一个重点了