Spring事务
程序员文章站
2022-05-20 09:39:48
...
Spring事务源码分析
一、Spring事务管理基本概念
1.1 什么是事务
1.2 事务的特性(ACID)
- 什么是ACID
ACID是指数据库管理系统DBMS中事务所具有的四个特性
在数据库系统中,一个事务由一系列的数据库操作组成一个完整的逻辑过程,比如银行转账:从原账户扣除金额,目标账户增加金额
1.2.1 atomicty原子性
原子性表现为操作不能被分割,那么这两个操作要么都完成,要么都不完成,若事务捕捉到异常了,那么事务就会回滚
1.2.2 Consistency一致性
数据库要一直处于一致的状态,事务开始前是一个状态,事务结束后是另外一个一致状态
1.2.3 Isolation隔离性
事务之间不会互相影响,如果一个事务要访问的数据正在被另外一个事务修改,只要另外一个事务还未提交,它所访问的数据就不受未提交事务的影响,换句话说,一个事务的影响在该事务提交前对其他事务是不可见的
1.2.4 Durability持久性
若事务已经提交了,那么事务就会在数据库汇总永久的保存下来
二、Spring事务三大接口
2.1 PlatformTransactionManager事务管理器
public interface PlatformTransactionManager {
/**
* 获取事务状态
*/
TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException;
/**
* 事务提交
*/
void commit(TransactionStatus status) throws TransactionException;
/**
* 事务回滚
*/
void rollback(TransactionStatus status) throws TransactionException;
}
2.2、TransactionDefinition事务定义信息(事务隔离级别、传播行为、超时、只读、回滚规则)
TransactionDefinition接口中定义了5个方法以及一些表示事务属性的常量比如隔离级别、传播行为等等常量
public interface TransactionDefinition {
// 支持当前事务,如果当前没有事务就创建一个事务
int PROPAGATION_REQUIRED = 0;
// 如果当前存在事务,则加入该事务,如果当前没有事务,则以非事务的方式继续执行
int PROPAGATION_SUPPORTS = 1;
// 如果当前存在事务,则加入该事务,如果当前没有事务,则抛出异常
int PROPAGATION_MANDATORY = 2;
// 创建一个新的事务,如果当前存在事务,则把当前事务挂起
int PROPAGATION_REQUIRES_NEW = 3;
// 以非事务方式运行,如果当前存在事务,则把当前事务挂起
int PROPAGATION_NOT_SUPPORTED = 4;
// 以非事务方式运行,如果当前存在事务,则把当前事务挂起
int PROPAGATION_NEVER = 5;
// 如果当有一个事务在运行中,则该方法应该运行在一个嵌套的事务中,被嵌套的事务可以独立运行于封装事务进行提交或者回滚,如果封装事务不存在,行为就像PROPAGATION_REQUIRES_NEW
int PROPAGATION_NESTED = 6;
// 使用数据库默认隔离级别,MySQL默认采用REPEATABLE_READ隔离级别,Orange默认采用READ_COMMITTED隔离级别
int ISOLATION_DEFAULT = -1;
// 最低的隔离级别,允许读取尚未提交的数据变更,可能会导致脏读、幻读和不可重复读
int ISOLATION_READ_UNCOMMITTED = Connection.TRANSACTION_READ_UNCOMMITTED;
// 允许读取并发事务已经提交的数据,可以阻止脏读,但是幻读和不可重复读仍有可能发生
int ISOLATION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED;
// 对同一字段的多次读取结果都是一样的,除非本数据是被本身事务修改,可以阻止脏读和不可重复读,但幻读仍有可能发生
int ISOLATION_REPEATABLE_READ = Connection.TRANSACTION_REPEATABLE_READ;
// 最高的隔离级别,完全服从ACID的隔离级别,所有的事务依次逐个执行,这样事务之间完全不可能产生干扰,也就是说,该级别可以防止幻读、脏读和不可重复读,当时这样严重影响程序的性能,通常情况下也不会用到该隔离级别
int ISOLATION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE;
// 使用默认的超时时间
int TIMEOUT_DEFAULT = -1;
/**
* 获取事务的传播行为
*/
int getPropagationBehavior();
/**
* 获取事务的隔离级别
*/
int getIsolationLevel();
/**
* 获取事务超时时间
*/
int getTimeout();
/**
* 判断当前事务是否为只读事务
*/
boolean isReadOnly();
/**
* 获取事务的名称
*/
String getName();
}
2.3、TransactionStatus事务运行状态
public interface TransactionStatus extends SavepointManager, Flushable {
/**
* 是否是新事务
*/
boolean isNewTransaction();
/**
* 是否有保存点
*/
boolean hasSavepoint();
/**
* 设置回滚
*/
void setRollbackOnly();
/**
* 判断设置了回滚
*/
boolean isRollbackOnly();
/**
* 属性
*/
void flush();
/**
*
*/
boolean isCompleted();
}
三、@EnableTransactionManagement注解
3.1 @EnableTransactionManagement
@Import:可以将组件导入IOC容器中
/**
* @Import注解可以为我们容器中导入组件TransactionManagementConfigurationSelector
*/
@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;
}
3.1.1 TransactionManagementConfigurationSelector
public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> {
/**
* 在加载IOC容器中加载bean定义的时候会回调selectImports方法
* 方法的返回值是我们需要导入的类的全类名路径,然后这个类就会被加载到容器中
*/
@Override
protected String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) {
/**
* 为我们的容器导入AutoProxyRegistrar和ProxyTransactionManagementConfiguration
*/
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;
}
}
}
3.1.1.1 AutoProxyRegistrar
public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
/**
* 实现了ImportBeanDefinitionRegistrar接口,在容器启动时候会回调registerBeanDefinitions方法添加InfrastructureAdvisorAutoProxyCreator这个组件到Spring容器中
* 往容器中添加BeanDefinition
* <p/>
* InfrastructureAdvisorAutoProxyCreator继承了AbstractAutoProxyCreator,AbstractAutoProxyCreator实现了BeanPostProcessor接口
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
boolean candidateFound = false;
Set<String> annTypes = importingClassMetadata.getAnnotationTypes();
for (String annType : annTypes) {
AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
if (candidate == null) {
continue;
}
Object mode = candidate.get("mode");
Object proxyTargetClass = candidate.get("proxyTargetClass");
if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() &&
Boolean.class == proxyTargetClass.getClass()) {
candidateFound = true;
if (mode == AdviceMode.PROXY) {
// 导入InfrastructureAdvisorAutoProxyCreator这个组件到IOC容器中,它实现了BeanPostProcessor接口
AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
if ((Boolean) proxyTargetClass) {
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
return;
}
}
}
}
if (!candidateFound && logger.isWarnEnabled()) {
String name = getClass().getSimpleName();
logger.warn(String.format("%s was imported but no annotations were found " + "having both 'mode' and 'proxyTargetClass' attributes of type " +"AdviceMode and boolean respectively. This means that auto proxy " +"creator registration and configuration may not have occurred as " +"intended, and components may not be proxied as expected. Check to " +"ensure that %s has been @Import'ed on the same class where these " +"annotations are declared; otherwise remove the import of %s " +"altogether.", name, name, name));
}
}
}
public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
return registerAutoProxyCreatorIfNecessary(registry, null);
}
public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, @Nullable Object source) {
return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
}
3.1.1.2 ProxyTransactionManagementConfiguration
/**
* 往IOC容器中添加BeanFactoryTransactionAttributeSourceAdvisor、TransactionAttributeSource、TransactionInterceptor三个组件bean
* BeanFactoryTransactionAttributeSourceAdvisor实现了PointcutAdvisor接口
*/
@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;
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public TransactionAttributeSource transactionAttributeSource() {
return new AnnotationTransactionAttributeSource();
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public TransactionInterceptor transactionInterceptor() {
TransactionInterceptor interceptor = new TransactionInterceptor();
interceptor.setTransactionAttributeSource(transactionAttributeSource());
if (this.txManager != null) {
interceptor.setTransactionManager(this.txManager);
}
return interceptor;
}
}
四、事务源码
4.1 doGetBean(name, null, null, false)
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
// 这一大段代码省略
......
// 真正创建bean
return createBean(beanName, mbd, args);
// 这一大段代码省略
......
}
4.2 createBean(beanName, mbd, args)
/**
* Spring Aop功能是使用Spring提供的扩展点BeanPostProcessor后置处理器来实现对切面信息的读取和缓存
*/
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
// 这一大段代码省略
......
// 通过bean的后置处理器进行后置处理解析Aop和事务信息
// 主要是来执行实现了InstantiationAwareBeanPostProcessor接口的BeanPostProcesser
// AOP核心方法,用来处理使用@Aspect注解标识的切面bean,读取切面bean中的信息,添加到advisorsCache缓存中,以便后面生成动态代理
// 事务核心方法
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
// 实例化bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
// 这一大段代码省略
......
}
五、切面信息的读取和缓存
5.1 resolveBeforeInstantiation(beanName, mbdToUse)
/**
* AOP/事务核心方法,用来处理使用@Aspect注解标识的切面bean,读取切面bean中的信息,添加到advisorsCache缓存中,以便后面生成动态代理
*/
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
// 检测是否被解析过
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
// hasInstantiationAwareBeanPostProcessors()是来判断容器中是否有InstantiationAwareBeanPostProcessor的实现bean
// AOP/事务切面后置处理器AspectJAwareAdvisorAutoProxyCreator就实现了InstantiationAwareBeanPostProcessor接口
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd); // 获取bean的目标类型
if (targetType != null) {
// 执行实现了InstantiationAwareBeanPostProcessor接口的BeanPostProcessor中的前置处理方法postProcessBeforeInstantiation方法
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
// 执行实现了InstantiationAwareBeanPostProcessor接口的BeanPostProcessor中的后置处理方法postProcessAfterInitialization方法
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
5.1.1 applyBeanPostProcessorsBeforeInstantiation(targetType, beanName)
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
/**
* 开启Aop的@EnableAspectJAutoProxy为我们的容器中导入了AnnotationAwareAspectJAutoProxyCreator,该类间接继承自AbstractAutoProxyCreator类
* 开启事务的@EnableTransactionManagement为我们的容器中导入了InfrastructureAdvisorAutoProxyCreator,该类间接继承自AbstractAutoProxyCreator类
* 都是实现了BeanPostProcessor接口,InstantiationAwareBeanPostProcessor接口
*/
// 当processor的实现类是AbstractAutoProxyCreator时将会调用AbstractAutoProxyCreator对postProcessAfterInitialization方法的实现来生成动态代理的代理对象
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
5.1.2 processor.postProcessAfterInitialization(result, beanName)
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
if (bean != null) {
// 获取在解析AOP/事务信息时添加的缓存
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
// 生成动态代理对象
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
5.1.3 wrapIfNecessary(bean, beanName, cacheKey)
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
// isInfrastructureClass(bean.getClass()):判断这个bean是不是有没有实现Advice、PuintCut、Advisor、AopInfrastructureBean接口
// shouldSkip(bean.getClass(), beanName):应不应该跳过
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
// 获取AOP切面和切面方法
// 获取事务的Advisor增强器对象
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;
}
5.1.3.1 getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource)
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
// 在IOC容器中寻找需要增强器
List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
if (advisors.isEmpty()) {
return DO_NOT_PROXY;
}
return advisors.toArray();
}
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
// 在IOC容器中寻找需要增强器
List<Advisor> candidateAdvisors = findCandidateAdvisors();
// 判断这些增强器能不能用在当前类上
List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
// 添加Spring提供的增强器
extendAdvisors(eligibleAdvisors);
// 对增强器进行排序
if (!eligibleAdvisors.isEmpty()) {
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
}
return eligibleAdvisors;
}
5.1.3.1.1 findCandidateAdvisors()
protected List<Advisor> findCandidateAdvisors() {
Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
return this.advisorRetrievalHelper.findAdvisorBeans();
}
public List<Advisor> findAdvisorBeans() {
String[] advisorNames = this.cachedAdvisorBeanNames;
if (advisorNames == null) {
// 在BeanFactory中获取类型为Advisor的bean集合
advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Advisor.class, true, false);
this.cachedAdvisorBeanNames = advisorNames;
}
// 当不存在类型为Advisor的bean,直接返回
if (advisorNames.length == 0) {
return new ArrayList<>();
}
// 遍历类型为Advisor的bean集合,根据bean名称集合获取bean的实例集合
List<Advisor> advisors = new ArrayList<>();
for (String name : advisorNames) {
if (isEligibleBean(name)) {
if (this.beanFactory.isCurrentlyInCreation(name)) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping currently created advisor '" + name + "'");
}
}
else {
try {
// 根据bean的名称从BeanFactory中获取bean实例
advisors.add(this.beanFactory.getBean(name, Advisor.class));
}
catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
if (rootCause instanceof BeanCurrentlyInCreationException) {
BeanCreationException bce = (BeanCreationException) rootCause;
String bceBeanName = bce.getBeanName();
if (bceBeanName != null && this.beanFactory.isCurrentlyInCreation(bceBeanName)) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping advisor '" + name + "' with dependency on currently created bean: " + ex.getMessage());
}
continue;
}
}
throw ex;
}
}
}
}
return advisors;
}
5.1.3.1.2 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 {
// 从线程局部变量中清除当前正在创建的beanName的代理对象名称
ProxyCreationContext.setCurrentProxiedBeanName(null);
}
}
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
// 若候选的增强器集合为空,直接返回
if (candidateAdvisors.isEmpty()) {
return candidateAdvisors;
}
// 循环候选的增强器集合
List<Advisor> eligibleAdvisors = new ArrayList<>();
for (Advisor candidate : candidateAdvisors) {
// 判断增强器是不是实现了IntroductionAdvisor接口(很明显事务接口没有实现,不会走下面的逻辑)
if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
eligibleAdvisors.add(candidate);
}
}
boolean hasIntroductions = !eligibleAdvisors.isEmpty();
for (Advisor candidate : candidateAdvisors) {
// 判断增强器是不是实现了IntroductionAdvisor接口(很明显事务接口没有实现,不会走下面的逻辑)
if (candidate instanceof IntroductionAdvisor) {
continue;
}
// 判断这个增强器是不是我们合适的
if (canApply(candidate, clazz, hasIntroductions)) {
eligibleAdvisors.add(candidate);
}
}
return eligibleAdvisors;
}
public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
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;
}
// MethodMatcher是一个方法匹配器,在这里是用于匹配class对象的方法是否含有@Transactional注解
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 = null;
if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
}
Set<Class<?>> classes = new LinkedHashSet<>();
if (!Proxy.isProxyClass(targetClass)) {
classes.add(ClassUtils.getUserClass(targetClass));
}
// 获取到targetClass所实现的接口的class对象,然后添加到集合中
classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
// 循环所有的class对象
for (Class<?> clazz : classes) {
// 获取class对象中所有的方法
Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
// 循环class对象中所有的方法
for (Method method : methods) {
if (introductionAwareMethodMatcher != null ?
introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :
methodMatcher.matches(method, targetClass)) {
return true;
}
}
}
return false;
}
// TransactionAttributeSourcePointcut类
public boolean matches(Method method, @Nullable Class<?> targetClass) {
if (targetClass != null && TransactionalProxy.class.isAssignableFrom(targetClass)) {
return false;
}
TransactionAttributeSource tas = getTransactionAttributeSource();
return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}
public boolean matches(Method method, @Nullable Class<?> targetClass) {
if (targetClass != null && TransactionalProxy.class.isAssignableFrom(targetClass)) {
return false;
}
// 获取@EnableTransactionalManager为我们导入的ProxyTransactionManagementConfiguration组件bean
// 从中获取配置类中的TransactionAttributeSource对象,TransactionAttributeSource是通过ProxyTransactionManagementConfiguration组件bean导入到IOC容器中
TransactionAttributeSource tas = getTransactionAttributeSource();
// 获取事务属性
return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}
// AbstractFallbackTransactionAttributeSource类
public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
// 判断method所在的类是不是Object类型
if (method.getDeclaringClass() == Object.class) {
return null;
}
// 获取缓存key
Object cacheKey = getCacheKey(method, targetClass);
// 从缓存中获取value值
TransactionAttribute cached = this.attributeCache.get(cacheKey);
// 缓存中存在
if (cached != null) {
// 判断缓存中的对象是不是空事务对象
if (cached == NULL_TRANSACTION_ATTRIBUTE) {
return null;
}
// 不是的话就返回
else {
return cached;
}
}
// 缓存中不存在
else {
// 获取@Transactional事务注解中的事务属性
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, @Nullable Class<?> targetClass) {
// 判断事务方法是不是public的
if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
return null;
}
// @Transactional注解可以放在实现类的方法上、实现类的类上、接口方法上、接口类的类上
// 这里主要是获取@Transactional注解所在的位置,如果在方法上,specificMethod = method,如果在类上,specificMethod != method
Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
// 获取目标方法上的事务属性
TransactionAttribute txAttr = findTransactionAttribute(specificMethod);
if (txAttr != null) {
return txAttr;
}
// 获取方法所在类上的事务属性
txAttr = findTransactionAttribute(specificMethod.getDeclaringClass());
if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
return txAttr;
}
if (specificMethod != method) {
// 获取接口方法上的事务属性
txAttr = findTransactionAttribute(method);
if (txAttr != null) {
return txAttr;
}
// 获取接口方法所在接口上的事务属性
txAttr = findTransactionAttribute(method.getDeclaringClass());
if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
return txAttr;
}
}
return null;
}
1.1.3.1.2.1 findTransactionAttribute(method)
protected TransactionAttribute findTransactionAttribute(Method method) {
return determineTransactionAttribute(method);
}
protected TransactionAttribute determineTransactionAttribute(AnnotatedElement element) {
// 获取注解解析器
for (TransactionAnnotationParser annotationParser : this.annotationParsers) {
// 通过注解解析器去解析方法上的注解
TransactionAttribute attr = annotationParser.parseTransactionAnnotation(element);
if (attr != null) {
return attr;
}
}
return null;
}
public TransactionAttribute parseTransactionAnnotation(AnnotatedElement element) {
// 获取@Transactional注解对象,然后把注解属性封装到AnnotationAttributes对象中
AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(
element, Transactional.class, false, false);
if (attributes != null) {
// 解析事务属性对象
return parseTransactionAnnotation(attributes);
}
else {
return null;
}
}
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());
// 解析timeout事务超时时间
rbta.setTimeout(attributes.getNumber("timeout").intValue());
rbta.setReadOnly(attributes.getBoolean("readOnly"));
// 解析value事务管理器名称
rbta.setQualifier(attributes.getString("value"));
List<RollbackRuleAttribute> rollbackRules = new ArrayList<>();
// 解析rollbackFor针对哪种异常回滚
for (Class<?> rbRule : attributes.getClassArray("rollbackFor")) {
rollbackRules.add(new RollbackRuleAttribute(rbRule));
}
// 解析rollbackForClassName针对哪种异常进行回滚
for (String rbRule : attributes.getStringArray("rollbackForClassName")) {
rollbackRules.add(new RollbackRuleAttribute(rbRule));
}
// 解析noRollbackFor针对哪种异常不回滚
for (Class<?> rbRule : attributes.getClassArray("noRollbackFor")) {
rollbackRules.add(new NoRollbackRuleAttribute(rbRule));
}
// 解析noRollbackForClassName针对哪种类型不回滚
for (String rbRule : attributes.getStringArray("noRollbackForClassName")) {
rollbackRules.add(new NoRollbackRuleAttribute(rbRule));
}
rbta.setRollbackRules(rollbackRules);
return rbta;
}
5.1.3.2 createProxy(beanClass, beanName, specificInterceptors, targetSource)
/**
* 创建事务动态代理对象
*/
protected Object createProxy(Class<?> beanClass, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource) {
if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
}
// 生成动态代理工厂
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.copyFrom(this);
if (!proxyFactory.isProxyTargetClass()) {
if (shouldProxyTargetClass(beanClass, beanName)) {
proxyFactory.setProxyTargetClass(true);
}
else {
evaluateProxyInterfaces(beanClass, proxyFactory);
}
}
// 获取Advisor增强器对象
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 Object getProxy(@Nullable ClassLoader classLoader) {
return createAopProxy().getProxy(classLoader);
}
/**
* 从动态代理工厂中获取代理对象
*/
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}
/**
* 使用动态代理工厂来创建代理对象
*/
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
// config.isProxyTargetClass()默认值为false
// hasNoUserSuppliedProxyInterfaces(config)判断该bean是否是接口,如果是接口,直接使用JDK动态代理
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.");
}
// ProxyTargetClass为true时使用Cglib动态代理
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
// 否则为JDK动态代理
return new ObjenesisCglibAopProxy(config);
}
// 当ProxyTargetClass为false 或者 该bean时接口时 使用JDK动态代理
else {
return new JdkDynamicAopProxy(config);
}
}
六、存储动态代理对象
在经过Object beanInstance = doCreateBean(beanName, mbdToUse, args);
获取了bean实例,将其返回给方法调用的createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
方法,然后再返回给调用的getSingleton(String beanName, ObjectFactory<?> singletonFactory)
方法
6.1 getSingleton(String beanName, ObjectFactory<?> singletonFactory)
/**
* 获取单例的bean实例,如果bean实例不存在的话就创建
* 从addSingleton(beanName, singletonObject)可以看出,最后生成的代理对象和普通bean一样被添加到singletonObjects单例池(一级缓存)中
*/
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
// 这一大块代码省略
......
// 调用ObjectFactory接口实现类中的getObject()方法,这里是使用lambad表达式来进行重新getObject()方法的
singletonObject = singletonFactory.getObject();
// 这一大块代码省略
......
// 将singletonObject添加到singletonObjects一级缓存中,同时将二级、三级缓存中的bean删除
addSingleton(beanName, singletonObject);
return singletonObject;
}
}
七、调用代理方法
7.1 invoke(proxy, method, args)
/**
* 也就是当Proxy对象的代理方法被调用时,JdkDynamicAopProxy的的invoke方法作为Proxy对象的回调函数被触发,从而通过invoke的具体实现,来完成对目标对象方法调用的拦截或者说功能的增强工作
* 在Proxy.newProxyInstance(classLoader, proxiedInterfaces, this)生成动态代理对象时,this需要时实现了InvocationHandler接口,并重写invoke()方法,在invoke()方法中定义代理对象的逻辑
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
Object target = null;
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
return equals(args[0]);
}
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
return hashCode();
}
else if (method.getDeclaringClass() == DecoratingProxy.class) {
return AopProxyUtils.ultimateTargetClass(this.advised);
}
else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
Object retVal;
if (this.advised.exposeProxy) {
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null);
// 根据切面方法获取拦截器链
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
// 如果拦截器链不存在,就直接调用目标对象的方法
if (chain.isEmpty()) {
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
// 如果拦截器链存在,就对目标对象的方法进行增强
// 需要在调用目标对象的方法前后调用拦截器方法
else {
// 根据proxy(代理对象)、target(目标对象)、method(方法对象)、args(目标对象调用的方法参数)、targetClass(目标对象的Class对象)、chain(拦截器链)来生成拦截器链
MethodInvocation invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
// 通过责任链模式来连接拦截器链
retVal = invocation.proceed();
}
Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target &&
returnType != Object.class && returnType.isInstance(proxy) &&
!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
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) {
AopContext.setCurrentProxy(oldProxy);
}
}
}
7.1.1 invocation.proceed()
public Object proceed() throws Throwable {
// 从-1开始计数
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
// 调用目标对象方法
return invokeJoinpoint();
}
// 从拦截器链中获取MethodInterceptor拦截器,然后currentInterceptorIndex并进行++currentInterceptorIndex
Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
// 如果MethodInterceptor拦截器是InterceptorAndDynamicMethodMatcher类型的
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
InterceptorAndDynamicMethodMatcher dm = (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
// 这里每一次都去匹配是否适用于这个目标方法
if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
}
else {
// 递归调用,进行下一个拦截器链进行调用
return proceed();
}
}
else {
// 这里this为当前ReflectiveMethodInvocation对象
// 在invoke()方法中也进行递归调用
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
7.1.1.1 invoke(invocation)
public Object invoke(MethodInvocation invocation) throws Throwable {
// 获取目标类对象
Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
// 执行事务
return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
}
protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass, final InvocationCallback invocation) throws Throwable {
// 获取事务属性源对象
TransactionAttributeSource tas = getTransactionAttributeSource();
// 通过事务属性源对象获取事务属性信息
final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
// 读取配置的事务管理器对象
final PlatformTransactionManager tm = determineTransactionManager(txAttr);
// 从事务属性对象中获取@Transactional方法描述符
final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
// 声明式事务
if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
// 如果需要的话创建事务
TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
Object retVal;
try {
// 回调目标方法
retVal = invocation.proceedWithInvocation();
}
catch (Throwable ex) {
// 捕捉到异常进行事务回滚
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
finally {
// 清空事务信息
cleanupTransactionInfo(txInfo);
}
// 事务提交
commitTransactionAfterReturning(txInfo);
return retVal;
}
// 编程式事务
else {
final ThrowableHolder throwableHolder = new ThrowableHolder();
try {
Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr, status -> {
TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
try {
return invocation.proceedWithInvocation();
}
catch (Throwable ex) {
if (txAttr.rollbackOn(ex)) {
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
else {
throw new ThrowableHolderException(ex);
}
}
else {
throwableHolder.throwable = ex;
return null;
}
}
finally {
cleanupTransactionInfo(txInfo);
}
});
if (throwableHolder.throwable != null) {
throw throwableHolder.throwable;
}
return result;
}
catch (ThrowableHolderException ex) {
throw ex.getCause();
}
catch (TransactionSystemException ex2) {
if (throwableHolder.throwable != null) {
logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
ex2.initApplicationException(throwableHolder.throwable);
}
throw ex2;
}
catch (Throwable ex2) {
if (throwableHolder.throwable != null) {
logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
}
throw ex2;
}
}
}
protected TransactionInfo createTransactionIfNecessary(@Nullable PlatformTransactionManager tm, @Nullable 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");
}
}
}
// 把事务的状态和事务属性等信息封装成TransactionInfo对象
return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
}
public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException {
Object transaction = doGetTransaction();
boolean debugEnabled = logger.isDebugEnabled();
// 获取调用事务方法的事务信息
if (isExistingTransaction(transaction)) {
// 如果当前环境是有事务的情况下
return handleExistingTransaction(definition, transaction, debugEnabled);
}
// 检查@Transactional注解中定义的timeout属性的值
if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
}
// 当事务的传播属性是MANDATORY
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
throw new IllegalTransactionStateException(
"No existing transaction found for transaction marked with propagation 'mandatory'");
}
// 当事务的传播属性是REQUIRED、REQUIRES_NEW、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 | Error ex) {
resume(null, suspendedResources);
throw ex;
}
}
// 不使用事务
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);
}
}
private TransactionStatus handleExistingTransaction(TransactionDefinition definition, Object transaction, boolean debugEnabled) throws TransactionException {
// 当事务的传播属性是NEVER,抛出异常
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
throw new IllegalTransactionStateException("Existing transaction found for transaction marked with propagation 'never'");
}
// 当事务的传播属性是NOT_SUPPORTED,挂起当前事务
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
if (debugEnabled) {
logger.debug("Suspending current transaction");
}
Object suspendedResources = suspend(transaction);
boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
return prepareTransactionStatus(
definition, null, false, newSynchronization, debugEnabled, suspendedResources);
}
// 当事务的传播属性是REQUIRES_NEW,挂起当前事务并创建一个新的事务
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
if (debugEnabled) {
logger.debug("Suspending current transaction, creating new transaction with name [" + definition.getName() + "]");
}
SuspendedResourcesHolder suspendedResources = suspend(transaction);
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 | Error beginEx) {
resumeAfterBeginException(transaction, suspendedResources, beginEx);
throw beginEx;
}
}
// 当事务的传播属性是NESTED
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
// 判断是否允许使用NESTED的方式处理
if (!isNestedTransactionAllowed()) {
throw new NestedTransactionNotSupportedException("Transaction manager does not allow nested transactions by default - " + "specify 'nestedTransactionAllowed' property with value 'true'");
}
if (debugEnabled) {
logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
}
// 是否支持保存点的方式,创建嵌套事务保存点的方式来进行事务的提交
if (useSavepointForNestedTransaction()) {
DefaultTransactionStatus status =
prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
status.createAndHoldSavepoint();
return status;
}
// 创建一个新的事务
else {
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, null);
doBegin(transaction, definition);
prepareSynchronization(status, definition);
return status;
}
}
// Assumably PROPAGATION_SUPPORTS or PROPAGATION_REQUIRED.
if (debugEnabled) {
logger.debug("Participating in existing transaction");
}
// 使用当前事务
if (isValidateExistingTransaction()) {
if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
Integer currentIsolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
if (currentIsolationLevel == null || currentIsolationLevel != definition.getIsolationLevel()) {
Constants isoConstants = DefaultTransactionDefinition.constants;
throw new IllegalTransactionStateException("Participating transaction with definition [" + definition + "] specifies isolation level which is incompatible with existing transaction: " + (currentIsolationLevel != null ? isoConstants.toCode(currentIsolationLevel, DefaultTransactionDefinition.PREFIX_ISOLATION) : "(unknown)"));
}
}
if (!definition.isReadOnly()) {
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
throw new IllegalTransactionStateException("Participating transaction with definition [" + definition + "] is not marked as read-only but existing transaction is");
}
}
}
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
}
下一篇: Git入门第十二讲:分支管理