Notice
I wrote this article and was originally published on Qiita on 12 September 2019.
Proxy class is created when class is annotated with @Transactional
In my notice board example application, class info.saladlam.example.spring.noticeboard.service.MessageServiceImpl is annotated with @Transactional. When bean factory processes this class, proxy instance of this class, with org.springframework.transaction.interceptor.TransactionInterceptor set is created. You may view the actual instance of MessageService from Eclipse's debugger.
Function of TransactionInterceptor
- Send begin transaction and commit signal to PlatformTransactionManager instance
- Handling exception case
Below is code from method org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(Method, Class<?>, InvocationCallback).
// ...
// If the transaction attribute is null, the method is non-transactional.
TransactionAttributeSource tas = getTransactionAttributeSource();
final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
final org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(Method, Class<?>, InvocationCallback) tm = determineTransactionManager(txAttr);
final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
// Standard transaction demarcation with getTransaction and commit/rollback calls.
TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
Object retVal;
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.proceedWithInvocation();
}
catch (Throwable ex) {
// target invocation exception
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
finally {
cleanupTransactionInfo(txInfo);
}
commitTransactionAfterReturning(txInfo);
return retVal;
}
// ...
When program executes to
retVal = invocation.proceedWithInvocation();
method of info.saladlam.example.spring.noticeboard.service.MessageServiceImpl is called.
Function of PlatformTransactionManager
In Spring Framework context there is a singleton PlatformTransactionManager instance. In this application, the implementation is org.springframework.jdbc.datasource.DataSourceTransactionManager. This class is for handle all transaction action happened.