一 事务信息配置
- 配置事务管理器及数据库连接池
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
- 配置事务注解@Transactional处理,注入事务管理器
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
- 注入事务管理器
transactionManager
到事务调用代理函数TransactionInterceptor
中,代理类调用时用于创建并管理事务。
RootBeanDefinition interceptorDef = new RootBeanDefinition(TransactionInterceptor.class);
interceptorDef.setSource(eleSource);
interceptorDef.setRole(2);
AnnotationDrivenBeanDefinitionParser.registerTransactionManager(element, interceptorDef);
interceptorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName));
String interceptorName = parserContext.getReaderContext().registerWithGeneratedName(interceptorDef);
-
TransactionInterceptor
实现接口MethodInterceptor
用于aop代理调用
public interface MethodInterceptor extends Interceptor {
/**
* Implement this method to perform extra treatments before and
* after the invocation. Polite implementations would certainly
* like to invoke {@link Joinpoint#proceed()}.
*
* @param invocation the method invocation joinpoint
* @return the result of the call to {@link
* Joinpoint#proceed()}, might be intercepted by the
* interceptor.
*
* @throws Throwable if the interceptors or the
* target-object throws an exception. */
Object invoke(MethodInvocation invocation) throws Throwable;
}
- 封装Advisor类,aop创建代理类时会获取advisor接口实现类,匹配待创建的bean,匹配成功则创建aop代理。
RootBeanDefinition advisorDef = new RootBeanDefinition(BeanFactoryTransactionAttributeSourceAdvisor.class);
advisorDef.setSource(eleSource);
advisorDef.setRole(2);
//pointcut 切入点,通过注解参数初始化
advisorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName));
//advise 通知,代理调用
advisorDef.getPropertyValues().add("adviceBeanName", interceptorName);
if(element.hasAttribute("order")) {
advisorDef.getPropertyValues().add("order", element.getAttribute("order"));
}
parserContext.getRegistry().registerBeanDefinition(txAdvisorBeanName, advisorDef);
- aop调用
TransactionAttributeSourcePointcut
类方法match匹配目标类方法是否需要创建事务代理
@Override
public boolean matches(Method method, Class<?> targetClass) {
if (TransactionalProxy.class.isAssignableFrom(targetClass)) {
return false;
}
TransactionAttributeSource tas = getTransactionAttributeSource();
return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}
二 事务创建流程
spring事务.png