Low-level AOP infrastructure for transaction proxying. These classes provide the foundation for declarative transaction management and are typically used when implementing custom transaction behavior or framework extensions.
Base class for transactional aspects such as TransactionInterceptor. Provides the underlying Spring transaction infrastructure for implementing aspects for any aspect system.
/**
* Base class for transactional aspects enabling the Spring transaction
* infrastructure to be used easily to implement an aspect for any aspect system.
* Subclasses are responsible for calling methods in this class in the correct order.
*/
public abstract class TransactionAspectSupport
implements BeanFactoryAware, InitializingBean {
/**
* Subclasses can use this to return the current TransactionInfo.
* Used by AspectJ aspects involving distinct before and after advice.
*/
protected static @Nullable TransactionInfo currentTransactionInfo()
throws NoTransactionException;
/**
* Return the transaction status of the current method invocation.
* Mainly intended for code that wants to set the current transaction
* rollback-only but not throw an application exception.
*/
public static TransactionStatus currentTransactionStatus()
throws NoTransactionException;
/**
* Create a new TransactionAspectSupport.
*/
protected TransactionAspectSupport();
/**
* Specify the name of the default transaction manager bean.
*/
public void setTransactionManagerBeanName(@Nullable String transactionManagerBeanName);
/**
* Specify the default transaction manager to use to drive transactions.
*/
public void setTransactionManager(@Nullable TransactionManager transactionManager);
/**
* Return the default transaction manager, or null if unknown.
*/
public @Nullable TransactionManager getTransactionManager();
/**
* Set properties with method names as keys and transaction attribute
* descriptors (parsed via TransactionAttributeEditor) as values.
*/
public void setTransactionAttributes(Properties transactionAttributes);
/**
* Set multiple transaction attribute sources which are used to find
* transaction attributes. Builds a CompositeTransactionAttributeSource.
*/
public void setTransactionAttributeSources(
TransactionAttributeSource... transactionAttributeSources
);
/**
* Set the transaction attribute source which is used to find transaction
* attributes.
*/
public void setTransactionAttributeSource(
@Nullable TransactionAttributeSource transactionAttributeSource
);
/**
* Return the transaction attribute source.
*/
public @Nullable TransactionAttributeSource getTransactionAttributeSource();
/**
* Set the BeanFactory to use for retrieving TransactionManager beans.
*/
@Override
public void setBeanFactory(@Nullable BeanFactory beanFactory);
/**
* Check that required properties were set.
*/
@Override
public void afterPropertiesSet();
/**
* General delegate for around-advice-based subclasses, delegating to several
* other template methods on this class. Able to handle CallbackPreferringPlatformTransactionManager
* as well as regular PlatformTransactionManager implementations and ReactiveTransactionManager
* implementations for reactive return types.
*/
protected @Nullable Object invokeWithinTransaction(
Method method,
@Nullable Class<?> targetClass,
InvocationCallback invocation
) throws Throwable;
/**
* Create a transaction if necessary based on the given TransactionAttribute.
*/
protected TransactionInfo createTransactionIfNecessary(
@Nullable PlatformTransactionManager tm,
@Nullable TransactionAttribute txAttr,
String joinpointIdentification
);
/**
* Execute after successful completion of call, but not after an exception was handled.
*/
protected void commitTransactionAfterReturning(@Nullable TransactionInfo txInfo);
/**
* Handle a throwable, completing the transaction.
*/
protected void completeTransactionAfterThrowing(
@Nullable TransactionInfo txInfo,
Throwable ex
);
/**
* Reset the TransactionInfo ThreadLocal.
*/
protected void cleanupTransactionInfo(@Nullable TransactionInfo txInfo);
/**
* Callback interface for proceeding with the target invocation.
*/
protected interface InvocationCallback {
@Nullable Object proceedWithInvocation() throws Throwable;
}
/**
* Opaque object used to hold transaction information.
*/
protected static final class TransactionInfo {
public TransactionInfo(
@Nullable PlatformTransactionManager transactionManager,
@Nullable TransactionAttribute transactionAttribute,
String joinpointIdentification
);
public @Nullable PlatformTransactionManager getTransactionManager();
public @Nullable TransactionAttribute getTransactionAttribute();
public String getJoinpointIdentification();
public boolean hasTransaction();
}
}Usage Example:
import org.springframework.transaction.interceptor.TransactionAspectSupport;
// Access current transaction status from within transactional code
@Transactional
public void processOrder(Order order) {
try {
// Business logic
orderRepository.save(order);
inventoryService.decrementStock(order);
} catch (OutOfStockException ex) {
// Mark transaction for rollback without throwing exception
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
order.setStatus(OrderStatus.PENDING);
orderRepository.save(order);
}
}AOP Alliance MethodInterceptor for declarative transaction management using method attributes.
/**
* AOP Alliance MethodInterceptor for declarative transaction management.
* Delegates to a TransactionAttributeSource for determining transaction attributes.
*/
public class TransactionInterceptor extends TransactionAspectSupport
implements MethodInterceptor, Serializable {
/**
* Create a new TransactionInterceptor.
*/
public TransactionInterceptor();
/**
* Create a new TransactionInterceptor with the given transaction manager
* and transaction attributes.
*/
public TransactionInterceptor(
PlatformTransactionManager transactionManager,
TransactionAttributeSource transactionAttributeSource
);
/**
* AOP Alliance invoke method. Delegates to superclass for transaction handling.
*/
@Override
public Object invoke(MethodInvocation invocation) throws Throwable;
}Usage Example:
@Configuration
public class ManualTransactionProxyConfig {
@Bean
public ProxyFactoryBean serviceProxy(
Service target,
PlatformTransactionManager transactionManager) {
ProxyFactoryBean proxyFactory = new ProxyFactoryBean();
proxyFactory.setTarget(target);
// Create transaction interceptor
TransactionInterceptor interceptor = new TransactionInterceptor(
transactionManager,
new AnnotationTransactionAttributeSource()
);
proxyFactory.addAdvice(interceptor);
return proxyFactory;
}
}Strategy interface for retrieving transaction attributes for methods and classes.
/**
* Strategy for metadata retrieval. Implementations know how to source
* transaction attributes, whether from source-level annotations, XML, etc.
*/
public interface TransactionAttributeSource {
/**
* Determine whether the given class is a candidate for transaction attributes.
* Used for optimization to avoid attribute lookup for non-transactional classes.
*/
default boolean isCandidateClass(Class<?> targetClass);
/**
* Determine whether there is a transaction attribute for the given method.
* Optimization method to avoid full attribute retrieval.
*/
default boolean hasTransactionAttribute(Method method, Class<?> targetClass);
/**
* Return the transaction attribute for the given method, or null if not transactional.
*/
TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass);
}Extended TransactionDefinition interface with additional metadata for transaction management.
/**
* Extended TransactionDefinition interface that adds qualifier and rollback rules.
*/
public interface TransactionAttribute extends TransactionDefinition {
/**
* Return a qualifier value for the transaction manager.
*/
String getQualifier();
/**
* Return labels associated with the transaction for monitoring/diagnostics.
*/
Collection<String> getLabels();
/**
* Determine whether to rollback on the given exception.
*/
boolean rollbackOn(Throwable ex);
}TransactionAttribute implementation with rollback rules.
/**
* TransactionAttribute implementation that determines rollback behavior
* based on configured RollbackRuleAttributes.
*/
public class RuleBasedTransactionAttribute extends DefaultTransactionAttribute {
/**
* Create a new RuleBasedTransactionAttribute.
*/
public RuleBasedTransactionAttribute();
/**
* Copy constructor.
*/
public RuleBasedTransactionAttribute(RuleBasedTransactionAttribute other);
/**
* Set the list of RollbackRuleAttribute objects.
*/
public void setRollbackRules(List<RollbackRuleAttribute> rollbackRules);
/**
* Get the rollback rules.
*/
public List<RollbackRuleAttribute> getRollbackRules();
}Rule determining rollback behavior for specific exceptions.
/**
* Rule determining whether to rollback on a given exception.
*/
public class RollbackRuleAttribute implements Serializable {
/**
* Constant for rollback on all runtime exceptions.
*/
public static final RollbackRuleAttribute ROLLBACK_ON_RUNTIME_EXCEPTIONS =
new RollbackRuleAttribute(RuntimeException.class);
/**
* Constant for rollback on all exceptions.
*/
public static final RollbackRuleAttribute ROLLBACK_ON_ALL_EXCEPTIONS =
new RollbackRuleAttribute(Exception.class);
/**
* Create a RollbackRuleAttribute for the given exception type.
*/
public RollbackRuleAttribute(Class<?> clazz);
/**
* Create a RollbackRuleAttribute for the given exception name pattern.
*/
public RollbackRuleAttribute(String exceptionName);
/**
* Return the depth of the match (0 = exact, higher = superclass).
*/
public int getDepth(Throwable ex);
}
/**
* Tag subclass of RollbackRuleAttribute indicating that no rollback should occur.
*/
public class NoRollbackRuleAttribute extends RollbackRuleAttribute {
public NoRollbackRuleAttribute(Class<?> clazz);
public NoRollbackRuleAttribute(String exceptionName);
}Usage Example:
// Create transaction attribute with rollback rules
RuleBasedTransactionAttribute attribute = new RuleBasedTransactionAttribute();
attribute.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
attribute.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
List<RollbackRuleAttribute> rollbackRules = new ArrayList<>();
rollbackRules.add(new RollbackRuleAttribute(BusinessException.class));
rollbackRules.add(new NoRollbackRuleAttribute(ValidationException.class));
attribute.setRollbackRules(rollbackRules);
// Use in transaction attribute source
Map<String, TransactionAttribute> txAttributes = new HashMap<>();
txAttributes.put("create*", attribute);TransactionAttributeSource implementation for annotation-based transaction management.
/**
* Implementation of TransactionAttributeSource for annotation-based
* transaction demarcation. Supports Spring's @Transactional, JTA's @Transactional,
* and EJB3's @TransactionAttribute.
*/
public class AnnotationTransactionAttributeSource
extends AbstractFallbackTransactionAttributeSource implements Serializable {
/**
* Create a default AnnotationTransactionAttributeSource.
*/
public AnnotationTransactionAttributeSource();
/**
* Create an AnnotationTransactionAttributeSource with public methods only flag.
*/
public AnnotationTransactionAttributeSource(boolean publicMethodsOnly);
}Simple TransactionAttributeSource implementation based on method name patterns.
/**
* Simple TransactionAttributeSource implementation that allows transaction
* attributes to be matched by method name patterns.
*/
public class NameMatchTransactionAttributeSource
extends AbstractFallbackTransactionAttributeSource implements Serializable {
/**
* Set a map of method name patterns to TransactionAttributes.
*/
public void setNameMap(Map<String, TransactionAttribute> nameMap);
/**
* Add an attribute for a transactional method name pattern.
*/
public void addTransactionalMethod(String methodName, TransactionAttribute attr);
}Usage Example:
@Bean
public TransactionInterceptor transactionInterceptor(
PlatformTransactionManager transactionManager) {
NameMatchTransactionAttributeSource source =
new NameMatchTransactionAttributeSource();
// Define transaction attributes
RuleBasedTransactionAttribute readOnlyAttribute =
new RuleBasedTransactionAttribute();
readOnlyAttribute.setReadOnly(true);
readOnlyAttribute.setPropagationBehavior(
TransactionDefinition.PROPAGATION_SUPPORTS
);
RuleBasedTransactionAttribute writeAttribute =
new RuleBasedTransactionAttribute();
writeAttribute.setPropagationBehavior(
TransactionDefinition.PROPAGATION_REQUIRED
);
// Map patterns to attributes
source.addTransactionalMethod("get*", readOnlyAttribute);
source.addTransactionalMethod("find*", readOnlyAttribute);
source.addTransactionalMethod("load*", readOnlyAttribute);
source.addTransactionalMethod("*", writeAttribute);
return new TransactionInterceptor(transactionManager, source);
}Advisor driven by TransactionAttributeSource, used to include transaction infrastructure bean in proxies.
/**
* Advisor driven by a TransactionAttributeSource, used to include a
* transaction interceptor bean in auto-proxy infrastructure.
*/
public class BeanFactoryTransactionAttributeSourceAdvisor
extends AbstractBeanFactoryPointcutAdvisor {
/**
* Set the TransactionAttributeSource for this advisor.
*/
public void setTransactionAttributeSource(
TransactionAttributeSource transactionAttributeSource
);
/**
* Set the bean name of the TransactionInterceptor.
*/
public void setAdviceBeanName(String adviceBeanName);
/**
* Set the ClassFilter to use for this pointcut.
*/
public void setClassFilter(ClassFilter classFilter);
}FactoryBean for creating transactional proxies. Simplifies programmatic creation of transactional proxies for specific beans.
/**
* Proxy factory bean for simplified declarative transaction handling.
* Alternative to @Transactional annotation for programmatic proxy creation.
*/
public class TransactionProxyFactoryBean extends AbstractSingletonProxyFactoryBean {
private final TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
/**
* Set the transaction manager for this proxy.
*/
public void setTransactionManager(PlatformTransactionManager transactionManager);
/**
* Set transaction attributes as Properties (method name patterns as keys).
*/
public void setTransactionAttributes(Properties transactionAttributes);
/**
* Set the transaction attribute source directly.
*/
public void setTransactionAttributeSource(TransactionAttributeSource transactionAttributeSource);
/**
* Set the bean name of the TransactionManager.
*/
public void setTransactionManagerName(String transactionManagerName);
@Override
protected Object createMainInterceptor();
}Usage Example:
import org.springframework.transaction.interceptor.TransactionProxyFactoryBean;
@Configuration
public class TransactionProxyConfig {
@Bean
public TransactionProxyFactoryBean userService(
UserServiceTarget target,
PlatformTransactionManager txManager) {
TransactionProxyFactoryBean proxy = new TransactionProxyFactoryBean();
proxy.setTransactionManager(txManager);
proxy.setTarget(target);
Properties txAttributes = new Properties();
txAttributes.setProperty("get*", "PROPAGATION_SUPPORTS,readOnly");
txAttributes.setProperty("find*", "PROPAGATION_SUPPORTS,readOnly");
txAttributes.setProperty("save*", "PROPAGATION_REQUIRED");
txAttributes.setProperty("update*", "PROPAGATION_REQUIRED");
txAttributes.setProperty("delete*", "PROPAGATION_REQUIRED");
proxy.setTransactionAttributes(txAttributes);
return proxy;
}
}Advisor providing transaction advice based on a TransactionAttributeSource. Used internally to create transaction proxies.
/**
* Advisor driven by a TransactionAttributeSource.
* Used to build Spring AOP proxies for transactional methods.
*/
public class TransactionAttributeSourceAdvisor extends AbstractPointcutAdvisor {
private TransactionInterceptor transactionInterceptor;
private final TransactionAttributeSourcePointcut pointcut;
/**
* Create new advisor with default settings.
*/
public TransactionAttributeSourceAdvisor();
/**
* Create new advisor with given interceptor.
*/
public TransactionAttributeSourceAdvisor(TransactionInterceptor interceptor);
/**
* Set the transaction interceptor to use.
*/
public void setTransactionInterceptor(TransactionInterceptor transactionInterceptor);
/**
* Set the transaction attribute source.
*/
public void setTransactionAttributeSource(TransactionAttributeSource transactionAttributeSource);
/**
* Set the ClassFilter to use for the pointcut.
*/
public void setClassFilter(ClassFilter classFilter);
@Override
public Advice getAdvice();
@Override
public Pointcut getPointcut();
}Pointcut that matches transactional methods based on TransactionAttributeSource metadata.
/**
* Pointcut for transactional methods based on TransactionAttributeSource.
*/
public abstract class TransactionAttributeSourcePointcut
extends StaticMethodMatcherPointcut implements Serializable {
@Override
public boolean matches(Method method, Class<?> targetClass);
@Override
public boolean equals(Object other);
@Override
public int hashCode();
}Composite TransactionAttributeSource that delegates to multiple sources in order.
/**
* Composite TransactionAttributeSource implementation that iterates
* over an array of TransactionAttributeSource instances.
*/
public class CompositeTransactionAttributeSource
implements TransactionAttributeSource, Serializable {
/**
* Create new instance from array of attribute sources.
*/
public CompositeTransactionAttributeSource(
TransactionAttributeSource[] transactionAttributeSources
);
@Override
public boolean isCandidateClass(Class<?> targetClass);
@Override
public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass);
}Usage Example:
import org.springframework.transaction.interceptor.CompositeTransactionAttributeSource;
// Combine multiple attribute sources
TransactionAttributeSource composite = new CompositeTransactionAttributeSource(
new TransactionAttributeSource[] {
annotationAttributeSource, // Check annotations first
nameMatchAttributeSource, // Then name patterns
defaultAttributeSource // Finally defaults
}
);Simple TransactionAttributeSource that always returns the same TransactionAttribute for all methods.
/**
* Simple TransactionAttributeSource that always returns the same
* TransactionAttribute for all methods fed to it.
*/
public class MatchAlwaysTransactionAttributeSource
implements TransactionAttributeSource, Serializable {
/**
* Create new instance with default transaction attribute.
*/
public MatchAlwaysTransactionAttributeSource();
/**
* Set the transaction attribute to use.
*/
public void setTransactionAttribute(TransactionAttribute transactionAttribute);
@Override
public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass);
}Usage Example:
import org.springframework.transaction.interceptor.MatchAlwaysTransactionAttributeSource;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
// Apply same transaction attribute to all methods
MatchAlwaysTransactionAttributeSource source = new MatchAlwaysTransactionAttributeSource();
DefaultTransactionAttribute attr = new DefaultTransactionAttribute();
attr.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
attr.setReadOnly(false);
source.setTransactionAttribute(attr);TransactionAttributeSource that retrieves attributes based on fully-qualified method names.
/**
* TransactionAttributeSource that holds attributes keyed by fully-qualified method names.
*/
public class MethodMapTransactionAttributeSource extends MapTransactionAttributeSource {
/**
* Set a method map of transaction attributes.
* Keys are fully-qualified method names (e.g., "com.foo.Bar.myMethod").
*/
public void setMethodMap(Map<String, TransactionAttribute> methodMap);
/**
* Add a transactional method with its attribute.
*/
public void addTransactionalMethod(String name, TransactionAttribute attr);
}Abstract delegating TransactionAttribute implementation. Subclasses can override specific methods while delegating others.
/**
* Abstract TransactionAttribute implementation that delegates
* all calls to a target TransactionAttribute.
*/
public abstract class DelegatingTransactionAttribute
extends DelegatingTransactionDefinition implements TransactionAttribute, Serializable {
private final TransactionAttribute targetAttribute;
/**
* Create new DelegatingTransactionAttribute.
*/
public DelegatingTransactionAttribute(TransactionAttribute targetAttribute);
@Override
public String getQualifier();
@Override
public Collection<String> getLabels();
@Override
public boolean rollbackOn(Throwable ex);
}PropertyEditor for parsing transaction attribute strings into TransactionAttribute objects.
/**
* PropertyEditor for TransactionAttribute objects.
* Accepts String representations like "PROPAGATION_REQUIRED,timeout_5".
*/
public class TransactionAttributeEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text);
}Format: PROPAGATION_NAME[,ISOLATION_NAME][,readOnly][,timeout_NNNN][,+Exception1][-Exception2]
Example: "PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED,timeout_5,+IOException,-IllegalArgumentException"
TransactionInterceptor is the core component behind @TransactionalTransactionAttributeSource abstracts how transaction metadata is retrievedAnnotationTransactionAttributeSource is used by default for annotation-driven transactionsRollbackRuleAttribute determines exception-based rollback behaviorNoRollbackRuleAttribute to prevent rollback for specific exceptionsNameMatchTransactionAttributeSource useful for XML-based or programmatic configuration