1. /*
  2. * Copyright 2002-2004 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.transaction.interceptor;
  17. import java.util.Properties;
  18. import org.aopalliance.aop.AspectException;
  19. import org.aopalliance.intercept.MethodInterceptor;
  20. import org.aopalliance.intercept.MethodInvocation;
  21. import org.apache.commons.logging.Log;
  22. import org.apache.commons.logging.LogFactory;
  23. import org.springframework.beans.factory.InitializingBean;
  24. import org.springframework.transaction.NoTransactionException;
  25. import org.springframework.transaction.PlatformTransactionManager;
  26. import org.springframework.transaction.TransactionException;
  27. import org.springframework.transaction.TransactionStatus;
  28. /**
  29. * Interceptor providing declarative transaction management using the common
  30. * Spring transaction infrastructure. TransactionInterceptors are thread-safe.
  31. *
  32. * <p>Uses the <b>Strategy</b> design pattern. A PlatformTransactionManager
  33. * implementation will perform the actual transaction management.
  34. *
  35. * <p>This class could set JTA as default transaction manager as that
  36. * implementation does not need any specific configuration. JTA is
  37. * <i>not</i> the default though to avoid unnecessary dependencies.
  38. *
  39. * @version $Id: TransactionInterceptor.java,v 1.22 2004/05/23 20:14:16 jhoeller Exp $
  40. * @author Rod Johnson
  41. * @author Juergen Hoeller
  42. * @see org.springframework.aop.framework.ProxyFactoryBean
  43. * @see TransactionProxyFactoryBean
  44. * @see org.springframework.transaction.PlatformTransactionManager
  45. */
  46. public class TransactionInterceptor implements MethodInterceptor, InitializingBean {
  47. /** Holder to support the currentTransactionStatus() method */
  48. private static ThreadLocal currentTransactionStatus = new ThreadLocal();
  49. /**
  50. * Return the transaction status of the current method invocation.
  51. * Mainly intended for code that wants to set the current transaction
  52. * rollback-only but not throw an application exception.
  53. * @throws NoTransactionException
  54. * if the invocation cannot be found, because the method was invoked
  55. * outside an AOP invocation context
  56. */
  57. public static TransactionStatus currentTransactionStatus() throws AspectException {
  58. TransactionStatus status = (TransactionStatus) currentTransactionStatus.get();
  59. if (status == null) {
  60. throw new NoTransactionException("No TransactionInterceptor-managed TransactionStatus in scope");
  61. }
  62. return status;
  63. }
  64. protected final Log logger = LogFactory.getLog(getClass());
  65. /** Delegate used to create, commit and rollback transactions */
  66. private PlatformTransactionManager transactionManager;
  67. /** Helper used to find transaction attributes */
  68. private TransactionAttributeSource transactionAttributeSource;
  69. /**
  70. * Create a new TransactionInterceptor.
  71. * Does not set a default transaction manager!
  72. * @see #setTransactionManager
  73. * @see #setTransactionAttributeSource
  74. */
  75. public TransactionInterceptor() {
  76. }
  77. /**
  78. * Set the transaction manager. This will perform actual
  79. * transaction management: This class is just a way of invoking it.
  80. */
  81. public void setTransactionManager(PlatformTransactionManager transactionManager) {
  82. this.transactionManager = transactionManager;
  83. }
  84. /**
  85. * Return the transaction manager.
  86. */
  87. public PlatformTransactionManager getTransactionManager() {
  88. return transactionManager;
  89. }
  90. /**
  91. * Set properties with method names as keys and transaction attribute
  92. * descriptors (parsed via TransactionAttributeEditor) as values:
  93. * e.g. key = "myMethod", value = "PROPAGATION_REQUIRED,readOnly".
  94. * <p>Note: Method names are always applied to the target class,
  95. * no matter if defined in an interface or the class itself.
  96. * <p>Internally, a NameMatchTransactionAttributeSource will be
  97. * created from the given properties.
  98. * @see #setTransactionAttributeSource
  99. * @see TransactionAttributeEditor
  100. * @see NameMatchTransactionAttributeSource
  101. */
  102. public void setTransactionAttributes(Properties transactionAttributes) {
  103. NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
  104. tas.setProperties(transactionAttributes);
  105. this.transactionAttributeSource = tas;
  106. }
  107. /**
  108. * Set the transaction attribute source which is used to find transaction
  109. * attributes. If specifying a String property value, a PropertyEditor
  110. * will create a MethodMapTransactionAttributeSource from the value.
  111. * @see TransactionAttributeSourceEditor
  112. * @see MethodMapTransactionAttributeSource
  113. * @see NameMatchTransactionAttributeSource
  114. */
  115. public void setTransactionAttributeSource(TransactionAttributeSource transactionAttributeSource) {
  116. this.transactionAttributeSource = transactionAttributeSource;
  117. }
  118. /**
  119. * Return the transaction attribute source.
  120. */
  121. public TransactionAttributeSource getTransactionAttributeSource() {
  122. return transactionAttributeSource;
  123. }
  124. public void afterPropertiesSet() {
  125. if (this.transactionManager == null) {
  126. throw new IllegalArgumentException("transactionManager is required");
  127. }
  128. if (this.transactionAttributeSource == null) {
  129. throw new IllegalArgumentException("Either 'transactionAttributeSource' or 'transactionAttributes' " +
  130. "is required: If there are no transactional methods, don't use " +
  131. "a TransactionInterceptor respectively a transactional proxy.");
  132. }
  133. }
  134. public final Object invoke(MethodInvocation invocation) throws Throwable {
  135. // Work out the target class: may be null.
  136. // The TransactionAttributeSource should be passed the target class
  137. // as well as the method, which may be from an interface
  138. Class targetClass = (invocation.getThis() != null) ? invocation.getThis().getClass() : null;
  139. // if the transaction attribute is null, the method is non-transactional
  140. TransactionAttribute transAtt = this.transactionAttributeSource.getTransactionAttribute(invocation.getMethod(), targetClass);
  141. TransactionStatus status = null;
  142. TransactionStatus oldTransactionStatus = null;
  143. // create transaction if necessary
  144. if (transAtt != null) {
  145. // we need a transaction for this method
  146. if (logger.isDebugEnabled()) {
  147. logger.debug("Getting transaction for method '" + invocation.getMethod().getName() +
  148. "' in class [" + invocation.getMethod().getDeclaringClass().getName() + "]");
  149. }
  150. // the transaction manager will flag an error if an incompatible tx already exists
  151. status = this.transactionManager.getTransaction(transAtt);
  152. // make the TransactionStatus available to callees
  153. oldTransactionStatus = (TransactionStatus) currentTransactionStatus.get();
  154. currentTransactionStatus.set(status);
  155. }
  156. else {
  157. // it isn't a transactional method
  158. if (logger.isDebugEnabled())
  159. logger.debug("Don't need to create transaction for method '" + invocation.getMethod().getName() +
  160. "' in class [" + invocation.getMethod().getDeclaringClass().getName() +
  161. "]: this method isn't transactional");
  162. }
  163. // Invoke the next interceptor in the chain.
  164. // This will normally result in a target object being invoked.
  165. Object retVal = null;
  166. try {
  167. retVal = invocation.proceed();
  168. }
  169. catch (Throwable ex) {
  170. // target invocation exception
  171. if (status != null) {
  172. onThrowable(invocation, transAtt, status, ex);
  173. }
  174. throw ex;
  175. }
  176. finally {
  177. if (transAtt != null) {
  178. // use stack to restore old transaction status if one was set
  179. currentTransactionStatus.set(oldTransactionStatus);
  180. }
  181. }
  182. if (status != null) {
  183. if (logger.isDebugEnabled()) {
  184. logger.debug("Invoking commit for transaction on method '" + invocation.getMethod().getName() +
  185. "' in class [" + invocation.getMethod().getDeclaringClass().getName() + "]");
  186. }
  187. this.transactionManager.commit(status);
  188. }
  189. return retVal;
  190. }
  191. /**
  192. * Handle a throwable.
  193. * We may commit or roll back, depending on our configuration.
  194. */
  195. private void onThrowable(MethodInvocation invocation, TransactionAttribute txAtt,
  196. TransactionStatus status, Throwable ex) {
  197. if (txAtt.rollbackOn(ex)) {
  198. if (logger.isInfoEnabled()) {
  199. logger.info("Invoking rollback for transaction on method '" + invocation.getMethod().getName() +
  200. "' in class [" + invocation.getMethod().getDeclaringClass().getName() +
  201. "] due to throwable [" + ex + "]");
  202. }
  203. try {
  204. this.transactionManager.rollback(status);
  205. }
  206. catch (TransactionException tex) {
  207. logger.error("Application exception overridden by rollback exception", ex);
  208. throw tex;
  209. }
  210. }
  211. else {
  212. if (logger.isDebugEnabled()) {
  213. logger.debug("Method '" + invocation.getMethod().getName()+ "' in class [" +
  214. invocation.getMethod().getDeclaringClass().getName() +
  215. "] threw throwable [" + ex + "] but this does not force transaction rollback");
  216. }
  217. // will still roll back if rollbackOnly is true
  218. this.transactionManager.commit(status);
  219. }
  220. }
  221. }