有了上面的简单介绍就可以进入真正判断是否需要事务的地方了。这个方法在TransactionAspectSupport类里,
代码
-
-
-
-
-
-
-
-
- protected TransactionInfo createTransactionIfNecessary(Method method, Class targetClass) {
-
- final TransactionAttribute sourceAttr =
- this.transactionAttributeSource.getTransactionAttribute(method, targetClass);
- TransactionAttribute txAttr = sourceAttr;
-
-
- if (txAttr != null && txAttr.getName() == null) {
- final String name = methodIdentification(method);
- txAttr = new DelegatingTransactionAttribute(sourceAttr) {
- public String getName() {
- return name;
- }
- };
- }
-
- TransactionInfo txInfo = new TransactionInfo(txAttr, method);
-
- if (txAttr != null) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("Getting transaction for " + txInfo.joinpointIdentification());
- }
-
-
- txInfo.newTransactionStatus(this.transactionManager.getTransaction(txAttr));
- }
- else {
-
-
-
- if (logger.isDebugEnabled())
- logger.debug("Don't need to create transaction for [" + methodIdentification(method) +
- "]: this method isn't transactional");
- }
-
-
-
-
- txInfo.bindToThread();
- return txInfo;
- }
TransactionInfo是TransactionAspectSupport的一个内部类,它的主要功能是记录方法和对应的事务属性,在上面这个方法的最后,这个TransactionInfo对象被保存到当前线程中。
而这个方法会在事务拦截器TransactionInterceptor中被调用,TransactionInterceptor实际上是TransactionAspectSupport的子类,看看其中的invoke方法:
代码
- // Work out the target class: may be <code>null</code>.
- // The TransactionAttributeSource should be passed the target class
- // as well as the method, which may be from an interface
- Class targetClass = (invocation.getThis() != null) ? invocation.getThis().getClass() : null;
-
- // Create transaction if necessary.
- TransactionInfo txInfo = createTransactionIfNecessary(invocation.getMethod(), targetClass);
-
- Object retVal = null;
- try {
- // This is an around advice.
- // Invoke the next interceptor in the chain.
- // This will normally result in a target object being invoked.
- retVal = invocation.proceed();
- }
- catch (Throwable ex) {
- // target invocation exception
- doCloseTransactionAfterThrowing(txInfo, ex);
- throw ex;
- }
- finally {
- doFinally(txInfo);
- }
- doCommitTransactionAfterReturning(txInfo);//在这里执行方法结束之后需要的操作
- return retVal;
这个方法就如同一般的interceptor需要实现的方法一样。只不过在这个方法里判断被反射的方法是否需要事务。