以下内容衔接上篇文章
Spring 源码探索 之 声明式事务源码解读(一)
我们知道上图分析出,事物创建代理对象最最最主要的是InfrastructureAdvisorAutoProxyCreator这个类型作为
后置处理器为我们创建代理对象,实际上是他的父类AbstractAutoProxyCreator实现了postProcessBeforeInstantiation这个接口
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessBeforeInstantiation
我们分析代码得出,再InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation没有为我们做了什么事情,那么是怎么创建代理对象的?
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
Object cacheKey = getCacheKey(beanClass, beanName);
//判断我们的beanName以及是否处理过
if (beanName == null || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}
/*
*判断当前的bean是不是基础的bean或者直接跳过,不需要代理的
advice
Pointcut
Advisor
AopInfrastructureBean
**/
if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
/**
* 判断我们容器中有没有自定义的targetSource 有为我们自动创建对象
* 当时这一步的要求比较高,而且我们正常不会这里创建对象 ...
* */
if (beanName != null) {
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
this.targetSourcedBeans.add(beanName);
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
}
return null;
}
protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) {
//容器中必须要包含有个TargetSourceCreators 并且我们的组件也需要实现TargetSource接口
if (this.customTargetSourceCreators != null &&
this.beanFactory != null && this.beanFactory.containsBean(beanName)) {
for (TargetSourceCreator tsc : this.customTargetSourceCreators) {
TargetSource ts = tsc.getTargetSource(beanClass, beanName);
if (ts != null) {
// Found a matching TargetSource.
if (logger.isDebugEnabled()) {
logger.debug("TargetSourceCreator [" + tsc +
"] found custom TargetSource for bean with name '" + beanName + "'");
}
return ts;
}
}
}
return null;
}
我们知道图可知分析出,事物创建代理对象最最最主要的是InfrastructureAdvisorAutoProxyCreator这个类型作为
后置处理器为我们创建代理对象,实际上是他的父类AbstractAutoProxyCreator实现了 postProcessAfterInitialization这个接口
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator# postProcessAfterInitialization
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (!this.earlyProxyReferences.contains(cacheKey)) {
//当前对象是否需要包装
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
//判断代理对象再postProcessAfterInitialization接口中是否被处理过
if (beanName != null && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
//是否为基础的Bean 或者该对象不应该被调用
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
//找到我们容器中所有的增强器
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
//增强器不为空
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
//创建代理对象
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean(AbstractAutoProxyCreator的子类)
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) {
//找到合适的增强器
List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
//增强器为空,不需要代理
if (advisors.isEmpty()) {
return DO_NOT_PROXY;
}
//返回增强器
return advisors.toArray();
}
/*
*找到合适的增强器
**/
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
//找到候选的增强器
List<Advisor> candidateAdvisors = findCandidateAdvisors();
//从候选的中挑选出合适的增强器
List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
//增强器进行扩展
extendAdvisors(eligibleAdvisors);
//对增强器进行排序
if (!eligibleAdvisors.isEmpty()) {
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
}
return eligibleAdvisors;
}
==========================================findCandidateAdvisors();==================================================
/**
* 找到候选的增强器
* */
protected List<Advisor> findCandidateAdvisors() {
//通过我们我们增强器探测工具找
return this.advisorRetrievalHelper.findAdvisorBeans();
}
org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper#findAdvisorBeans
public List<Advisor> findAdvisorBeans() {
//看我们类级别缓存中有没有
String[] advisorNames = this.cachedAdvisorBeanNames;
if (advisorNames == null) {
//去容器中查找实现了我们Advisor接口的实现类 的名称:(org.springframework.transaction.config.internalTransactionAdvisor 类型为BeanFactoryTransactionAttributeSourceAdvisor)
advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Advisor.class, true, false);
//放入到缓存中
this.cachedAdvisorBeanNames = advisorNames;
}
if (advisorNames.length == 0) {
return new ArrayList<Advisor>();
}
List<Advisor> advisors = new ArrayList<Advisor>();
//循环我们的增强器
for (String name : advisorNames) {
//判断是不是合适的
if (isEligibleBean(name)) {
//当前的增强器是不是正在创建的
if (this.beanFactory.isCurrentlyInCreation(name)) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping currently created advisor '" + name + "'");
}
}
else {
try {
//通过getBean的显示调用获取BeanFactoryTransactionAttributeSourceAdvisor 组件
advisors.add(this.beanFactory.getBean(name, Advisor.class));
}
catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
if (rootCause instanceof BeanCurrentlyInCreationException) {
BeanCreationException bce = (BeanCreationException) rootCause;
if (this.beanFactory.isCurrentlyInCreation(bce.getBeanName())) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping advisor '" + name +
"' with dependency on currently created bean: " + ex.getMessage());
}
// Ignore: indicates a reference back to the bean we're trying to advise.
// We want to find advisors other than the currently created bean itself.
continue;
}
}
throw ex;
}
}
}
}
return advisors;
}
/**
* 判断包含是否为合适的最终逻辑
* 容器中的bean定义包含当前的增强器的bean定义,且bean的role是int ROLE_INFRASTRUCTURE = 2;
* */
protected boolean isEligibleAdvisorBean(String beanName) {
return (this.beanFactory.containsBeanDefinition(beanName) &&
this.beanFactory.getBeanDefinition(beanName).getRole() == BeanDefinition.ROLE_INFRASTRUCTURE);
}
================================================ findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);===============================
protected List<Advisor> findAdvisorsThatCanApply(
List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
ProxyCreationContext.setCurrentProxiedBeanName(beanName);
try {
//真正的去候选的增强器中找到当前能用的增强器
return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
}
finally {
ProxyCreationContext.setCurrentProxiedBeanName(null);
}
}
org.springframework.aop.support.AopUtils#findAdvisorsThatCanApply
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
//若传入进来的候选增强器为空直接返回
if (candidateAdvisors.isEmpty()) {
return candidateAdvisors;
}
//创建一个本类能用的增前期集合
List<Advisor> eligibleAdvisors = new LinkedList<Advisor>();
//循环候选的增强器
for (Advisor candidate : candidateAdvisors) {
//判断增强器是不是实现了IntroductionAdvisor 很明显没实现该接口
if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
eligibleAdvisors.add(candidate);
}
}
boolean hasIntroductions = !eligibleAdvisors.isEmpty();
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor) {
// already processed
continue;
}
//正在找出能用的增强器
if (canApply(candidate, clazz, hasIntroductions)) {
eligibleAdvisors.add(candidate);
}
}
return eligibleAdvisors;
}
/**
* 判断当前增强器是否为本来能用的
* */
public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
//根据类的继承图 发现 BeanFactoryTransactionAttributeSourceAdvisor没实现IntroductionAdvisor接口
if (advisor instanceof IntroductionAdvisor) {
return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
}
//BeanFactoryTransactionAttributeSourceAdvisor实现了PointcutAdvisor接口
else if (advisor instanceof PointcutAdvisor) {
//强制转换为PointcutAdvisor
PointcutAdvisor pca = (PointcutAdvisor) advisor;
return canApply(pca.getPointcut(), targetClass, hasIntroductions);
}
else {
// It doesn't have a pointcut so we assume it applies.
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;
}
/**
* 获取切点中的方法匹配器 TransactionAttributeSourcePointcut
* 该切点在创建BeanFactoryTransactionAttributeSourceAdvisor的时候 创建了切点TransactionAttributeSourcePointcut
* */
MethodMatcher methodMatcher = pc.getMethodMatcher();
if (methodMatcher == MethodMatcher.TRUE) {
// No need to iterate the methods if we're matching any method anyway...
return true;
}
/**
* 判断方法匹配器是不是IntroductionAwareMethodMatcher
* */
IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
}
//获取当前类的实现接口类型
Set<Class<?>> classes = new LinkedHashSet<Class<?>>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
classes.add(targetClass);
//循环上一步的接口类型
for (Class<?> clazz : classes) {
//获取接口的所有方法
Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
//循环我们接口中的方法
for (Method method : methods) {
//正在进行匹配的是methodMatcher.matches(method, targetClass)这个逻辑
if ((introductionAwareMethodMatcher != null &&introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||
methodMatcher.matches(method, targetClass)) {
return true;
}
}
}
return false;
}
org.springframework.transaction.interceptor.TransactionAttributeSourcePointcut#matches
public boolean matches(Method method, Class<?> targetClass) {
if (targetClass != null && TransactionalProxy.class.isAssignableFrom(targetClass)) {
return false;
}
//获取我们的事物源对象(在ProxyTransactionManagementConfiguration配置类配置的这里获取)
TransactionAttributeSource tas = getTransactionAttributeSource();
//从事物源对象中获取事物属性
return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}
/**
* 获取事物属性对象
* */
public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass) {
if (method.getDeclaringClass() == Object.class) {
return null;
}
//通过目标类和目标类的接口方法 拼接缓存key
Object cacheKey = getCacheKey(method, targetClass);
//去缓存中获取
TransactionAttribute cached = this.attributeCache.get(cacheKey);
if (cached != null) {
//缓存中有 直接返回就可以了
if (cached == NULL_TRANSACTION_ATTRIBUTE) {
return null;
}
else {
return cached;
}
}
else {
//计算事物属性.
TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass);
//若事物属性为空.
if (txAttr == null) {
//在缓存中标识 为事物方法
this.attributeCache.put(cacheKey, NULL_TRANSACTION_ATTRIBUTE);
}
else {
String methodIdentification = ClassUtils.getQualifiedMethodName(method, targetClass);
//为事物属性设置方法描述符号
if (txAttr instanceof DefaultTransactionAttribute) {
((DefaultTransactionAttribute) txAttr).setDescriptor(methodIdentification);
}
if (logger.isDebugEnabled()) {
logger.debug("Adding transactional method '" + methodIdentification + "' with attribute: " + txAttr);
}
//加入到缓存
this.attributeCache.put(cacheKey, txAttr);
}
return txAttr;
}
}
/**
* 计算事物属性
* */
protected TransactionAttribute computeTransactionAttribute(Method method, Class<?> targetClass) {
//判断方法的修饰夫
if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
return null;
}
//忽略cglib的代理
Class<?> userClass = ClassUtils.getUserClass(targetClass);
/**
* method为接口中的方法,specificMethod为我们实现类方法
* */
Method specificMethod = ClassUtils.getMostSpecificMethod(method, userClass);
// If we are dealing with method with generic parameters, find the original method.
specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
// 找我们【实现类】中的【方法】上的事物属性
TransactionAttribute txAttr = findTransactionAttribute(specificMethod);
if (txAttr != null) {
return txAttr;
}
//【方法所在类】上有没有事物属性
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;
}
【接口上】
txAttr = findTransactionAttribute(method.getDeclaringClass());
if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
return txAttr;
}
}
return null;
}
/**
* 从方法上找事物属性对象
* */
protected TransactionAttribute findTransactionAttribute(Method method) {
return determineTransactionAttribute(method);
}
protected TransactionAttribute determineTransactionAttribute(AnnotatedElement element) {
//获取方法上的注解
if (element.getAnnotations().length > 0) {
//事物注解解析器
for (TransactionAnnotationParser annotationParser : this.annotationParsers) {
//解析我们的注解
TransactionAttribute attr = annotationParser.parseTransactionAnnotation(element);
if (attr != null) {
return attr;
}
}
}
return null;
}
/**
* 解析事物注解
* */
public TransactionAttribute parseTransactionAnnotation(AnnotatedElement element) {
//解析@Transactional属性对象
AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(
element, Transactional.class);
if (attributes != null) {
//真正的解析@Transactional属性
return parseTransactionAnnotation(attributes);
}
else {
return null;
}
}
/**
* 解析事物注解
* */
protected TransactionAttribute parseTransactionAnnotation(AnnotationAttributes attributes) {
RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute();
//传播行为
Propagation propagation = attributes.getEnum("propagation");
rbta.setPropagationBehavior(propagation.value());
//隔离级别
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"));
List<RollbackRuleAttribute> rollbackRules = new ArrayList<RollbackRuleAttribute>();
//事物回滚规则
for (Class<?> rbRule : attributes.getClassArray("rollbackFor")) {
rollbackRules.add(new RollbackRuleAttribute(rbRule));
}
//对哪个类进行回滚
for (String rbRule : attributes.getStringArray("rollbackForClassName")) {
rollbackRules.add(new RollbackRuleAttribute(rbRule));
}
//对哪些异常不回滚
for (Class<?> rbRule : attributes.getClassArray("noRollbackFor")) {
rollbackRules.add(new NoRollbackRuleAttribute(rbRule));
}
//对哪些类不回滚
for (String rbRule : attributes.getStringArray("noRollbackForClassName")) {
rollbackRules.add(new NoRollbackRuleAttribute(rbRule));
}
rbta.setRollbackRules(rollbackRules);
return rbta;
}
真正的创建代理对象org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy
protected Object createProxy(
Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
//暴露代理对象
if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
}
//创建代理工厂
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.copyFrom(this);
//判断是cglib代理还是jdk代理
if (!proxyFactory.isProxyTargetClass()) {
if (shouldProxyTargetClass(beanClass, beanName)) {
proxyFactory.setProxyTargetClass(true);
}
else {
evaluateProxyInterfaces(beanClass, proxyFactory);
}
}
//把合适的拦截器转为增强器
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
proxyFactory.addAdvisors(advisors);
proxyFactory.setTargetSource(targetSource);
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
//真正的创建代理对象
return proxyFactory.getProxy(getProxyClassLoader());
}
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
//标识的是接口或者
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
//创建cglib接口
return new ObjenesisCglibAopProxy(config);
}
else {
创建jdk代理
return new JdkDynamicAopProxy(config);
}
}
public Object getProxy(ClassLoader classLoader) {
if (logger.isDebugEnabled()) {
logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
}
Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
org.springframework.aop.framework.JdkDynamicAopProxy#invoke
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MethodInvocation invocation;
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
Class<?> targetClass = null;
Object target = null;
try {
Object retVal;
//暴露代理对象
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// May be null. Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
target = targetSource.getTarget();
if (target != null) {
targetClass = target.getClass();
}
//把增强器转为方法拦截器链条
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
//拦截器链为空,直接通过反射进行调用
if (chain.isEmpty()) {
//通过反射进行调用
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
//创建反射方法调用对象
invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
//通过方法拦截器进行拦截调用
retVal = invocation.proceed();
}
// Massage return value if necessary.
Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target &&
returnType != Object.class && returnType.isInstance(proxy) &&
!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
// Special case: it returned "this" and the return type of the method
// is type-compatible. Note that we can't help if the target sets
// a reference to itself in another returned object.
retVal = proxy;
}
else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
throw new AopInvocationException(
"Null return value from advice does not match primitive return type for: " + method);
}
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
// Must have come from TargetSource.
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}
org.springframework.aop.framework.ReflectiveMethodInvocation#proceed
public Object proceed() throws Throwable {
//当前下标从-1开始,若当前索引值=执行到最后一个拦截器的下标,就执行目标方法
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
//获取我们的方法拦截器(TransactionInterceptor)
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
// Evaluate dynamic method matcher here: static part will already have
// been evaluated and found to match.
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
}
else {
// Dynamic matching failed.
// Skip this interceptor and invoke the next in the chain.
return proceed();
}
}
else {
//事务拦截器进行调用
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
org.springframework.transaction.interceptor.TransactionInterceptor#invoke(事务拦截器进行调用)
public Object invoke(final MethodInvocation invocation) throws Throwable {
//获取代理对象的目标class
Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
//使用事务调用
return invokeWithinTransaction(invocation.getMethod(), targetClass, new InvocationCallback() {
//从这里触发调用目标方法的
public Object proceedWithInvocation() throws Throwable {
return invocation.proceed();
}
});
}
org.springframework.transaction.interceptor.TransactionAspectSupport#invokeWithinTransaction(事务调用)
protected Object invokeWithinTransaction(Method method, Class<?> targetClass, final InvocationCallback invocation)
throws Throwable {
//通过@EnableTransactionManager 到入了TransactionAttributeSource 可以获取出事务属性对象
final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
//获取工程中的事务管理器
final PlatformTransactionManager tm = determineTransactionManager(txAttr);
//获取我们需要切入的方法(也就是我们标识了@Transactional注解的方法)
final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
//再这里我们只看我们常用的事务管理器,很明显我们不会配置CallbackPreferringPlatformTransactionManager事务管理器
if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
//判断有没有必要开启事务
TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
Object retVal = null;
try {
//调用我们的目标方法
retVal = invocation.proceedWithInvocation();
}
catch (Throwable ex) {
//抛出异常进行回顾
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
finally {
//清除事务信息
cleanupTransactionInfo(txInfo);
}
//提交事务
commitTransactionAfterReturning(txInfo);
return retVal;
}
}
org.springframework.transaction.interceptor.TransactionAspectSupport#createTransactionIfNecessary
protected TransactionInfo createTransactionIfNecessary(
PlatformTransactionManager tm, TransactionAttribute txAttr, final String joinpointIdentification) {
//把事务属性包装为
if (txAttr != null && txAttr.getName() == null) {
txAttr = new DelegatingTransactionAttribute(txAttr) {
@Override
public String getName() {
return joinpointIdentification;
}
};
}
TransactionStatus status = null;
if (txAttr != null) {
if (tm != null) {
//获取一个事务状态
status = tm.getTransaction(txAttr);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +
"] because no transaction manager has been configured");
}
}
}
//准备事务信息
return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
}
org.springframework.transaction.support.AbstractPlatformTransactionManager#getTransaction
public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
1:)先去尝试开启一个事务
Object transaction = doGetTransaction();
// Cache debug flag to avoid repeated checks.
boolean debugEnabled = logger.isDebugEnabled();
//传入进来的事务定义为空
if (definition == null) {
//使用系统默认的
definition = new DefaultTransactionDefinition();
}
2:)//判断是否存在事务(若存在事务,在这边直接返回不走下面的处理了)
if (isExistingTransaction(transaction)) {
// Existing transaction found -> check propagation behavior to find out how to behave.
return handleExistingTransaction(definition, transaction, debugEnabled);
}
3:)判读事务超时
if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
}
//不存在事务,需要在这边判断(PROPAGATION_MANDATORY 标识要求当前允许的在事务中,但是第二步进行判断之后 说明这里没有事务)
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
throw new IllegalTransactionStateException(
"No existing transaction found for transaction marked with propagation 'mandatory'");
}
//PROPAGATION_REQUIRED
//PROPAGATION_REQUIRES_NEW
//PROPAGATION_NESTED
else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
//挂起当前事务,但是当前是没有事务的
SuspendedResourcesHolder suspendedResources = suspend(null);
if (debugEnabled) {
logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);
}
try {
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
//创建一个新的事物状态
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
//开启一个事物
doBegin(transaction, definition);
//准备事物同步
prepareSynchronization(status, definition);
return status;
}
catch (RuntimeException ex) {
resume(null, suspendedResources);
throw ex;
}
catch (Error err) {
resume(null, suspendedResources);
throw err;
}
}
else {
//创建一个空的事物.
if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {
logger.warn("Custom isolation level specified but no actual transaction initiated; " +
"isolation level will effectively be ignored: " + definition);
}
boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
return prepareTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);
}
}
================================================代码1处中的代码============================================
/**
* 第一次进来的时候,是没有事务持有对象
* */
protected Object doGetTransaction() {
//创建一个数据库事务管理器
DataSourceTransactionObject txObject = new DataSourceTransactionObject();
//设置一个事务保存点
txObject.setSavepointAllowed(isNestedTransactionAllowed());
//从事务同步管理器中获取连接持有器
ConnectionHolder conHolder =
(ConnectionHolder) TransactionSynchronizationManager.getResource(this.dataSource);
//把持有器设置到对象中
txObject.setConnectionHolder(conHolder, false);
//返回一个事务对象
return txObject;
}
//第一次进来不会走这个逻辑
protected boolean isExistingTransaction(Object transaction) {
//获取事务对象中的持有器
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
//持有器不为空且 有事务激活
return (txObject.hasConnectionHolder() && txObject.getConnectionHolder().isTransactionActive());
}
=====================handleExistingTransaction================================
/**
* 第一次调用的时候
* */
protected void doBegin(Object transaction, TransactionDefinition definition) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
Connection con = null;
try {
//第一次进来,事务持有器中是没有对象的,所以我们需要自己手动的设置进去
if (!txObject.hasConnectionHolder() ||
txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
//获取一个数据库连接
Connection newCon = this.dataSource.getConnection();
if (logger.isDebugEnabled()) {
logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
}
//把数据库连接封装为一个持有器对象并且设置到事务对象中
txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
}
/开始同步标志
txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
con = txObject.getConnectionHolder().getConnection();
//获取事务的隔离级别
Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
txObject.setPreviousIsolationLevel(previousIsolationLevel);
/**
* 关闭事务自动提交
* */
if (con.getAutoCommit()) {
txObject.setMustRestoreAutoCommit(true);
if (logger.isDebugEnabled()) {
logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
}
con.setAutoCommit(false);
}
//判断事务是不是为只读的事务
prepareTransactionalConnection(con, definition);
//设置事务激活
txObject.getConnectionHolder().setTransactionActive(true);
int timeout = determineTimeout(definition);
if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
}
//把数据源和事务持有器保存到事务同步管理器中
if (txObject.isNewConnectionHolder()) {
TransactionSynchronizationManager.bindResource(getDataSource(), txObject.getConnectionHolder());
}
}
catch (Throwable ex) {
if (txObject.isNewConnectionHolder()) {
//抛出异常,释放资源
DataSourceUtils.releaseConnection(con, this.dataSource);
txObject.setConnectionHolder(null, false);
}
throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
}
}
========================== prepareSynchronization(status, definition);把当前的事务设置到同步管理器中(为下次准备)===========================
protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition) {
if (status.isNewSynchronization()) {
//设置事务激活
TransactionSynchronizationManager.setActualTransactionActive(status.hasTransaction());
//设置隔离级别
TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(
definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT ?
definition.getIsolationLevel() : null);
//设置只读书屋
ransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly());
//设置事务的名称
TransactionSynchronizationManager.setCurrentTransactionName(definition.getName());
TransactionSynchronizationManager.initSynchronization();
}
}
=================================== //准备事务信息 prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
protected TransactionInfo prepareTransactionInfo(PlatformTransactionManager tm,
TransactionAttribute txAttr, String joinpointIdentification, TransactionStatus status) {
//把事务管理器,事务属性,连接点信息封装成为TransactionInfo
TransactionInfo txInfo = new TransactionInfo(tm, txAttr, joinpointIdentification);
if (txAttr != null) {
// We need a transaction for this method...
if (logger.isTraceEnabled()) {
logger.trace("Getting transaction for [" + txInfo.getJoinpointIdentification() + "]");
}
//设置事务状态
txInfo.newTransactionStatus(status);
}
else {
// The TransactionInfo.hasTransaction() method will return false. We created it only
// to preserve the integrity of the ThreadLocal stack maintained in this class.
if (logger.isTraceEnabled())
logger.trace("Don't need to create transaction for [" + joinpointIdentification +
"]: This method isn't transactional.");
}
//把事务信息绑定到当前线程上去
txInfo.bindToThread();
return txInfo;
}