Spring聲明式事務讓咱們從複雜的事務處理中獲得解脫,使咱們不再用去處理這些步驟:得到鏈接、關閉鏈接、事務提交和回滾操做。不再須要在事務相關方法中處理大量的try..catch..finally代碼。java
Spring中事務的使用雖然已經相對簡單的多,可是,仍是有不少的使用和配置規則,下面咱們開始咱們本章重點。mysql
一、事務保證數據一致性問題,只須要加上@Transactionalspring
二、純手寫SpringAop環繞通知+手動事務就能夠聲明事務sql
@Repository
public class OrderDao {
@Autowired()
private JdbcTemplate jdbcTemplate;
public void addOrder() {
jdbcTemplate.update("insert into order_info values(null,'mayikt','zhangsan','1111')");
}
}
@Configuration @ComponentScan("com.mayikt") @EnableTransactionManagement//開啓事務註解 public class MyConfig { //注入到ioc容器中 beanid =dataSource class=DataSource類的完整路徑地址 // 配置咱們的數據源 @Bean public DataSource dataSource() { MysqlDataSource mysqlDataSource = new MysqlDataSource(); mysqlDataSource.setUser("root"); mysqlDataSource.setPassword("root"); mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8"); mysqlDataSource.setDatabaseName("test"); return mysqlDataSource; } /** * 注入JdbcTemplate */ @Bean public JdbcTemplate jdbcTemplate() { return new JdbcTemplate(dataSource()); } @Bean public PlatformTransactionManager platformTransactionManager(){ return new DataSourceTransactionManager(dataSource()); } }
@Service public class OrderServiceImpl implements OrderService { @Autowired private OrderDao orderDao; @Transactional//開啓事務 public void addOrder() { try { orderDao.addOrder(); int i = 1 / 0; // 若是報錯的狀況下確定是會插入到數據庫中 } catch (Exception e) { } } }
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.5.RELEASE</version> </dependency> <!-- mysql 依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.5.RELEASE</version> </dependency> </dependencies>
@EnableTransactionManagement//開啓事務
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {
TransactionManagementConfigurationSelector的祖宗是ImportSelector
public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> { @Override protected String[] selectImports(AdviceMode adviceMode) { switch (adviceMode) { case PROXY: return new String[] {AutoProxyRegistrar.class.getName(), ProxyTransactionManagementConfiguration.class.getName()}; case ASPECTJ: return new String[] {TransactionManagementConfigUtils.TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME}; default: return null; } } }
public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {//向IOC容器中注入Bean對象 .... @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { .... if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() && Boolean.class == proxyTargetClass.getClass()) { candidateFound = true; if (mode == AdviceMode.PROXY) { AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry); if ((Boolean) proxyTargetClass) { AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry); return; } } } } .... }
public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) { return registerAutoProxyCreatorIfNecessary(registry, (Object)null); }
public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, @Nullable Object source) { return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source); }
將InfrastructureAdvisorAutoProxyCreator注入到IOC容器中:數據庫
InfrastructureAdvisorAutoProxyCreator的類圖以下:祖宗是BeanPostProcessor後置處理器,父類是AbstractAutoProxyCreater框架
回到registerOrEscalateApcAsRequired方法:beanid爲:internalAutoProxyCreator,value爲:InfrastructureAdvisorAutoProxyCreator對象ide
private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) { Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); if (registry.containsBeanDefinition("org.springframework.aop.config.internalAutoProxyCreator")) { BeanDefinition apcDefinition = registry.getBeanDefinition("org.springframework.aop.config.internalAutoProxyCreator"); if (!cls.getName().equals(apcDefinition.getBeanClassName())) { int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName()); int requiredPriority = findPriorityForClass(cls); if (currentPriority < requiredPriority) { apcDefinition.setBeanClassName(cls.getName()); } } return null; } else { RootBeanDefinition beanDefinition = new RootBeanDefinition(cls); beanDefinition.setSource(source); beanDefinition.getPropertyValues().add("order", -2147483648); beanDefinition.setRole(2); registry.registerBeanDefinition("org.springframework.aop.config.internalAutoProxyCreator", beanDefinition); return beanDefinition; } }
下面回到ProxyTransactionManagementConfiguration方法函數
protected String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) {
case PROXY:
return new String[] {AutoProxyRegistrar.class.getName(), ProxyTransactionManagementConfiguration.class.getName()};
case ASPECTJ:
return new String[] {TransactionManagementConfigUtils.TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME};
default:
return null;
}
}
@Configuration public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration { @Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME) @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() { BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor(); advisor.setTransactionAttributeSource(transactionAttributeSource()); advisor.setAdvice(transactionInterceptor()); if (this.enableTx != null) { advisor.setOrder(this.enableTx.<Integer>getNumber("order")); } return advisor; }
BeanId:transactionInterceptor;value爲:TransactionInterceptor這個對象源碼分析
打印全部註冊的Beanpost
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
myConfig
orderDao
orderServiceImpl
org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration
org.springframework.transaction.config.internalTransactionAdvisor
transactionAttributeSource
transactionInterceptor【】【】【】【】這裏
org.springframework.transaction.config.internalTransactionalEventListenerFactory
dataSource
jdbcTemplate
platformTransactionManager
org.springframework.aop.config.internalAutoProxyCreator【】【】【】【】這裏
加上@EnableTransactionManagement這個註解將 :TransactionInterceptor,和InternalAutoProxyCreator這兩個類注入到IOC容器中
下面重點分析這兩個類【transactionInterceptor】,【internalAutoProxyCreator】
從上面類結構可知:InfrastructureAdvisorAutoProxyCreator間接實現了SmartInstantiationAwareBeanPostProcessor,而SmartInstantiationAwareBeanPostProcessor又繼承自
InstantiationAwareBeanPostProcessor,也就是說在Spring中,全部的bean實例化時Spring都會保證調用其postProcessAfterInstantiation方法,其實現是在父類AbstractAutoProxyCreater中實現的。
咱們一旦把這個類:InfrastructureAdvisorAutoProxyCreator注入到容器中,Bean對象在初始化時,會判斷是否須要建立代理類。
進入AbstractAutoProxyCreater的後置處理器:
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException { if (bean != null) { //根據給定的bean的class和name構建出key,beanClassName_beanName Object cacheKey = this.getCacheKey(bean.getClass(), beanName); //是不是因爲避免循環依賴而建立bean的代理 if (!this.earlyProxyReferences.contains(cacheKey)) { return this.wrapIfNecessary(bean, beanName, cacheKey); } } return bean; }
這裏實現的主要目的是針對指定的bean進行封裝,固然首先要肯定是否須要封裝,檢測及封裝的工做都委託給了wrapIfNecessary函數進行。
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { //若是已經處理過 if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) { return bean; } else if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) { return bean; } else if (!this.isInfrastructureClass(bean.getClass()) && !this.shouldSkip(bean.getClass(), beanName)) { Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, (TargetSource)null); if (specificInterceptors != DO_NOT_PROXY) { this.advisedBeans.put(cacheKey, Boolean.TRUE); Object proxy = this.createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));//關鍵點,建立代理,對須要加強的bean建立代理(CGLIBProxy或者JDKProxy) this.proxyTypes.put(cacheKey, proxy.getClass()); return proxy; } else { this.advisedBeans.put(cacheKey, Boolean.FALSE); return bean; } } else { this.advisedBeans.put(cacheKey, Boolean.FALSE); return bean; } }
wrapIfNecessary函數功能實現起來很複雜,可是邏輯上仍是相對簡單,在wrapIfNecessary函數中主要作了如下工做:
- 找出指定bean對應的加強器【上篇文章詳細介紹了,殊途同歸】
- 根據找出的加強器建立代理【上篇文章詳細介紹了,殊途同歸】
下面簡單瀏覽下:
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) { List<Advisor> advisors = this.findEligibleAdvisors(beanClass, beanName); return advisors.isEmpty() ? DO_NOT_PROXY : advisors.toArray(); }
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) { List<Advisor> candidateAdvisors = this.findCandidateAdvisors();//尋找候選加強器,這裏不介紹了 List<Advisor> eligibleAdvisors = this.findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);//候選加強器中尋找匹配項,這裏分析下 .... }
protected List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) { .... try { var4 = AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass); .... }
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) { .... while(var3.hasNext()) { Advisor candidate = (Advisor)var3.next(); //首先處理引介加強 if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) { eligibleAdvisors.add(candidate); } } .... while(var7.hasNext()) { Advisor candidate = (Advisor)var7.next(); //對普通bean的處理 if (!(candidate instanceof IntroductionAdvisor) && canApply(candidate, clazz, hasIntroductions)) { eligibleAdvisors.add(candidate); } .... } }
public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) { if (advisor instanceof IntroductionAdvisor) { return ((IntroductionAdvisor)advisor).getClassFilter().matches(targetClass); } else if (advisor instanceof PointcutAdvisor) { PointcutAdvisor pca = (PointcutAdvisor)advisor; return canApply(pca.getPointcut(), targetClass, hasIntroductions); } else { return true; } }
public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) { Assert.notNull(pc, "Pointcut must not be null"); if (!pc.getClassFilter().matches(targetClass)) { return false; } else { MethodMatcher methodMatcher = pc.getMethodMatcher(); .... for(int var11 = 0; var11 < var10; ++var11) { Method method = var9[var11]; if (introductionAwareMethodMatcher != null && introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) || methodMatcher.matches(method, targetClass)) { return true; .... } } }
public boolean matches(Method method, @Nullable Class<?> targetClass) { .... //自定義標籤解析時注入 TransactionAttributeSource tas = getTransactionAttributeSource(); return (tas == null || tas.getTransactionAttribute(method, targetClass) != null); }
public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) { .... else { // We need to work it out. TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass); .... }
protected TransactionAttribute computeTransactionAttribute(Method method, @Nullable Class<?> targetClass) { .... //method表明接口中的方法,specificMethod表明實現類中的方法 Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass); // First try is the method in the target class. //查看方法中是否存在事務聲明 TransactionAttribute txAttr = findTransactionAttribute(specificMethod); if (txAttr != null) { return txAttr; } // Second try is the transaction attribute on the target class. txAttr = findTransactionAttribute(specificMethod.getDeclaringClass()); if (txAttr != null && ClassUtils.isUserLevelMethod(method)) { return txAttr; } //若是存在接口,則到接口中去尋找 if (specificMethod != method) { // Fallback is to look at the original method. txAttr = findTransactionAttribute(method); if (txAttr != null) { return txAttr; } // Last fallback is the class of the original method. txAttr = findTransactionAttribute(method.getDeclaringClass()); if (txAttr != null && ClassUtils.isUserLevelMethod(method)) { return txAttr; } } return null; }
對於事務屬性的獲取規則相信你們都已經很清楚了,若是方法中存在事務屬性,則使用方法上的屬性,不然使用方法所在類上的屬性,若是方法所在類的屬性上仍是沒有搜尋到對應的事務屬性,那麼再搜尋接口中的方法,再沒有的化,
最好嘗試搜尋接口的類上面的聲明。對於函數computeTransactionAttribute中的邏輯,就是搭建了一個執行框架而已,將搜尋事務屬性任務委託給了findTransactionAttribute方法去執行。下面看看這個方法。
protected TransactionAttribute findTransactionAttribute(Method method) { return determineTransactionAttribute(method); }
protected TransactionAttribute determineTransactionAttribute(AnnotatedElement ae) { for (TransactionAnnotationParser annotationParser : this.annotationParsers) { TransactionAttribute attr = annotationParser.parseTransactionAnnotation(ae); if (attr != null) { return attr; } } return null; }
public TransactionAttribute parseTransactionAnnotation(AnnotatedElement ae) { AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes( ae, Transactional.class, false, false); if (attributes != null) { return parseTransactionAnnotation(attributes); } else { return null; } }
到這塊,咱們就看到了咱們想看到的獲取註解標記的代碼。首先會判斷當前類是否含有Transactional註解,這是事務屬性的基礎,固然若是有的化會繼續調用parseTransactionAnnotation方法解析詳細的屬性
protected TransactionAttribute parseTransactionAnnotation(AnnotationAttributes attributes) { RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); //解析propagation Propagation propagation = attributes.getEnum("propagation"); rbta.setPropagationBehavior(propagation.value()); //解析isolation Isolation isolation = attributes.getEnum("isolation"); rbta.setIsolationLevel(isolation.value()); rbta.setTimeout(attributes.getNumber("timeout").intValue()); rbta.setReadOnly(attributes.getBoolean("readOnly")); rbta.setQualifier(attributes.getString("value")); ArrayList<RollbackRuleAttribute> rollBackRules = new ArrayList<>(); Class<?>[] rbf = attributes.getClassArray("rollbackFor"); for (Class<?> rbRule : rbf) { RollbackRuleAttribute rule = new RollbackRuleAttribute(rbRule); rollBackRules.add(rule); } String[] rbfc = attributes.getStringArray("rollbackForClassName"); for (String rbRule : rbfc) { RollbackRuleAttribute rule = new RollbackRuleAttribute(rbRule); rollBackRules.add(rule); } Class<?>[] nrbf = attributes.getClassArray("noRollbackFor"); for (Class<?> rbRule : nrbf) { NoRollbackRuleAttribute rule = new NoRollbackRuleAttribute(rbRule); rollBackRules.add(rule); } String[] nrbfc = attributes.getStringArray("noRollbackForClassName"); for (String rbRule : nrbfc) { NoRollbackRuleAttribute rule = new NoRollbackRuleAttribute(rbRule); rollBackRules.add(rule); } rbta.getRollbackRules().addAll(rollBackRules); return rbta; }
上面方法實現了對對應類或者方法的事務屬性解析,你會看到這個類中你所屬性的屬性。至此,事務功能的初始化工做便結束了
springaop在事務進行調用的時候會走transactionInterceptor進行攔截
執行目標方法,進入invoke()
1.@EnableTransactionManagement開啓到咱們的事務
2.@Import(TransactionManagementConfigurationSelector.class)
3. AdviceMode mode() default AdviceMode.PROXY;默認使用 PROXY選擇器
4.return new String[] {AutoProxyRegistrar.class.getName(), ProxyTransactionManagementConfiguration.class.getName()};
5.加上@EnableTransactionManagement這個註解將 :TransactionInterceptor,和InternalAutoProxyCreator這兩個類注入到IOC容器中
6.進入AbstractAutoProxyCreater的後置處理器的wrapIfNecessary方法針對指定bean進行封裝
####6.1.找出指定bean對應的加強器
####6.2.根據找出的加強器建立代理
7.執行目標方法
8.一旦出現異常,嘗試異常處理,默認 對(RuntimeException回滾)
9.提交事務前的事務信息清除
10.提交事務。
參考書籍:Spring源碼深度解析