咱們總結出AOP公式java
本質都是在內存中生成了新的字節碼類。spring
這節咱們看看事務是如何利用AOP實現的。緩存
@EnableTransactionManagement的@Import(TransactionManagementConfigurationSelector.class)引入TransactionManagementConfigurationSelector.class。此類app
@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;
}
}
複製代碼
PROXY:狀況下,會註冊兩個類:ide
實現了ImportBeanDefinitionRegistrar。其接口方法registerBeanDefinitions會向倉庫註冊Bean定義源碼分析
InfrastructureAdvisorAutoProxyCreator。 InfrastructureAdvisorAutoProxyCreator
繼承了AbstractAdvisorAutoProxyCreator間接繼承了AbstractAutoProxyCreator
post
在AOP代理生成那一節,咱們講過。AnnotationAwareAspectJAutoProxyCreator
也是間接繼承了AbstractAutoProxyCreator
。ui
在AOP實現原理中AbstractAutoProxyCreator
作了大部分工做。this
從這一點看,事務代理對象建立過程,與AOP代理對象過程是同樣的,關鍵就在這個AbstractAutoProxyCreator類spa
是一個@Configuration。有三個@Bean註解方法。
@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());
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;
}
}
複製代碼
1.BeanFactoryTransactionAttributeSourceAdvisor:
首先:transactionAdvisor()方法會向倉庫中註冊一個BeanFactoryTransactionAttributeSourceAdvisor。
從其繼承關係上看,他是一個Advisor,而且仍是PointcutAdvisor.關於Advisor,上節咱們分析過他是封裝了(Advice+Pointcut)
既然都有了Advisor了,那Advice和Pointcut在哪裏呢?
BeanFactoryTransactionAttributeSourceAdvisor有一個pointcut 屬性,會new 一個TransactionAttributeSourcePointcut。
private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut() {
@Override
protected TransactionAttributeSource getTransactionAttributeSource() {
return transactionAttributeSource;
}
};
複製代碼
從其繼承關係,咱們能夠看出他其實就是一個Pointcut。
至此,就剩下Advice沒有被發現。
2.TransactionAttributeSource: 其次:transactionAttributeSource()會向倉庫中註冊一個AnnotationTransactionAttributeSource。這個AnnotationTransactionAttributeSource幹嗎用的呢?
BeanFactoryTransactionAttributeSourceAdvisor.setTransactionAttributeSource(transactionAttributeSource())
屬性值
private TransactionAttributeSource transactionAttributeSource;
private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut() {
@Override
protected TransactionAttributeSource getTransactionAttributeSource() {
return transactionAttributeSource;
}
};
TransactionAttributeSourcePointcut的matche方法
@Override
public boolean matches(Method method, Class<?> targetClass) {
if (targetClass != null && TransactionalProxy.class.isAssignableFrom(targetClass)) {
return false;
}
TransactionAttributeSource tas = getTransactionAttributeSource();
return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}
複製代碼
AnnotationTransactionAttributeSource對象會賦值給BeanFactoryTransactionAttributeSourceAdvisor的transactionAttributeSource
屬性。pointcut
屬性初始化時,new 一個TransactionAttributeSourcePointcut類
並實現getTransactionAttributeSource()
方法,getTransactionAttributeSource()
方法正好返回了transactionAttributeSource
屬性。
也就是說TransactionAttributeSourcePointcut的getTransactionAttributeSource()方法返回的是AnnotationTransactionAttributeSource
3.TransactionInterceptor : 最後:transactionInterceptor()方法,會向倉庫中註冊一個TransactionInterceptor類。
TransactionInterceptor從繼承關係看他是一個Advice. 也就是加強器,是對事務真正處理地方。
有了Advice+Pointcut。Advice+Pointcut = Advisor 。 Advisor+TargetSource = Advised
有了Advised ,這樣spring事務不正是套用了AOP的基礎嗎。
在AOP源碼分析那一節,咱們講過,postProcessAfterInitialization後置初始化方法中,wrapIfNecessary 知足條件,才建立代理。
@Override
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;
}
複製代碼
而這個條件就是:getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null); 可以獲取適用於當前bean的Advisor
咱們回顧上節:
getAdvicesAndAdvisorsForBean 通過AbstractAdvisorAutoProxyCreator.findEligibleAdvisors
的調用,AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass)
的調用,最終會調用AopUtils.canApply
來判斷某個Advisor是否適用於當前類。
咱們來看看canApply方法
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 {
// It doesn't have a pointcut so we assume it applies.
return true;
}
}
複製代碼
上文提到,
因此此處會走: canApply(pca.getPointcut(), targetClass, hasIntroductions)分支。
pca.getPointcut()
返回的是TransactionAttributeSourcePointcut
進一步分析重載方法canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions)
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 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<Class<?>>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
classes.add(targetClass);
for (Class<?> clazz : classes) {
Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
for (Method method : methods) {
if ((introductionAwareMethodMatcher != null &&
introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||
methodMatcher.matches(method, targetClass)) {
return true;
}
}
}
return false;
}
複製代碼
TransactionAttributeSourcePointcut
的父類StaticMethodMatcherPointcut.classFilter= ClassFilter.TRUE
表示類檢查所有經過abstract class TransactionAttributeSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {
@Override
public boolean matches(Method method, Class<?> targetClass) {
if (targetClass != null && TransactionalProxy.class.isAssignableFrom(targetClass)) {
return false;
}
TransactionAttributeSource tas = getTransactionAttributeSource();
return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}
}
複製代碼
matches方法會調用getTransactionAttributeSource()
獲取一個TransactionAttributeSource
對象,經過TransactionAttributeSource.getTransactionAttribute(method, targetClass)
,來判斷適應性。
關於getTransactionAttributeSource()
上文講過。會返回一個AnnotationTransactionAttributeSource
實例對象。
也就是說:TransactionAttributeSourcePointcut 的 matches()方法是經過AnnotationTransactionAttributeSource.getTransactionAttribute(method, targetClass)來實現的。
來看看getTransactionAttribute()方法
@Override
public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass) {
if (method.getDeclaringClass() == Object.class) {
return null;
}
// First, see if we have a cached value.
Object cacheKey = getCacheKey(method, targetClass);
TransactionAttribute cached = this.attributeCache.get(cacheKey);
if (cached != null) {
// Value will either be canonical value indicating there is no transaction attribute,
// or an actual transaction attribute.
if (cached == NULL_TRANSACTION_ATTRIBUTE) {
return null;
}
else {
return cached;
}
}
else {
// We need to work it out.
TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass);
// Put it in the cache.
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;
}
}
複製代碼
這裏用了一個緩存,但重點在這個TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass);
protected TransactionAttribute computeTransactionAttribute(Method method, Class<?> targetClass) {
// Don't allow no-public methods as required.
// 非public方法事務不生效。
if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
return null;
}
// Ignore CGLIB subclasses - introspect the actual user class.
Class<?> userClass = ClassUtils.getUserClass(targetClass);
// The method may be on an interface, but we need attributes from the target class.
// If the target class is null, the method will be unchanged.
// 獲取真實的方法(有接口方法的,要獲取實現類上的那個方法)
Method specificMethod = ClassUtils.getMostSpecificMethod(method, userClass);
// If we are dealing with method with generic parameters, find the original method.
specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
// First try is the method in the target class.
//首先查看實現類方法上是否有@Transactional註解
TransactionAttribute txAttr = findTransactionAttribute(specificMethod);
if (txAttr != null) {
return txAttr;
}
// Second try is the transaction attribute on the target class.
//其次查看實現類方法所在類上是否有@Transactional註解
txAttr = findTransactionAttribute(specificMethod.getDeclaringClass());
if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
return txAttr;
}
if (specificMethod != method) {
// Fallback is to look at the original method.
//還不行去看接口方法上是否有@Transactional註解
txAttr = findTransactionAttribute(method);
if (txAttr != null) {
return txAttr;
}
// Last fallback is the class of the original method.
//最後看接口上是否有@Transactional註解
txAttr = findTransactionAttribute(method.getDeclaringClass());
if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
return txAttr;
}
}
return null;
}
複製代碼
由此:咱們們也終於知道,@Transactional註解的查找順序,實現類方法--》實現類--》接口方法--》接口 咱們在這四個地方添加@Transactional註解都會使事務生效。
在這四個地方任一一個地方找到了@Transactional註解,說明BeanFactoryTransactionAttributeSourceAdvisor
適用於當前類,getAdvicesAndAdvisorsForBean 的返回不爲空。接下來就能夠建立動態代理了。
// Create proxy if we have advice.
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;
}
複製代碼
createProxy()方法,在spring源碼系列8:AOP源碼解析之代理的建立一節咱們一節分析過了。
最終的結果就是經過 CglibAopProxy. getProxy()返回代理對象 或者 JdkDynamicAopProxy. getProxy()返回代理對象
spring事務,就是在spring AOP基礎上實現的。 經過定義一個適用於事務的Advisor(Advice+Pointcut)完美的套用AOP的東西,實現了事務。
咱們看看這個公式:
試想,若是咱們可不能夠利用這個公式也能建立出一個相似事務的東西呢?