Allow Propagation.NOT_SUPPORTED with @TransactionalEventListener

Closes gh-31907
This commit is contained in:
Juergen Hoeller 2023-12-26 10:59:19 +01:00
parent 17d362fa85
commit 75c7596259
2 changed files with 20 additions and 4 deletions

View File

@ -25,7 +25,8 @@ import org.springframework.transaction.event.TransactionalEventListenerFactory;
/**
* Extension of {@link TransactionalEventListenerFactory},
* detecting invalid transaction configuration for transactional event listeners:
* {@link Transactional} only supported with {@link Propagation#REQUIRES_NEW}.
* {@link Transactional} only supported with {@link Propagation#REQUIRES_NEW}
* and {@link Propagation#NEVER}.
*
* @author Juergen Hoeller
* @since 6.1
@ -37,9 +38,12 @@ public class RestrictedTransactionalEventListenerFactory extends TransactionalEv
@Override
public ApplicationListener<?> createApplicationListener(String beanName, Class<?> type, Method method) {
Transactional txAnn = AnnotatedElementUtils.findMergedAnnotation(method, Transactional.class);
if (txAnn != null && txAnn.propagation() != Propagation.REQUIRES_NEW) {
throw new IllegalStateException("@TransactionalEventListener method must not be annotated with " +
"@Transactional unless when declared as REQUIRES_NEW: " + method);
if (txAnn != null) {
Propagation propagation = txAnn.propagation();
if (propagation != Propagation.REQUIRES_NEW && propagation != Propagation.NOT_SUPPORTED) {
throw new IllegalStateException("@TransactionalEventListener method must not be annotated with " +
"@Transactional unless when declared as REQUIRES_NEW or NOT_SUPPORTED: " + method);
}
}
return super.createApplicationListener(beanName, type, method);
}

View File

@ -143,6 +143,13 @@ public class TransactionalApplicationListenerMethodAdapterTests {
assertThatNoException().isThrownBy(() -> factory.createApplicationListener("test", SampleEvents.class, m));
}
@Test
public void withTransactionalNotSupportedAnnotation() {
RestrictedTransactionalEventListenerFactory factory = new RestrictedTransactionalEventListenerFactory();
Method m = ReflectionUtils.findMethod(SampleEvents.class, "withTransactionalNotSupportedAnnotation", String.class);
assertThatNoException().isThrownBy(() -> factory.createApplicationListener("test", SampleEvents.class, m));
}
@Test
public void withAsyncTransactionalAnnotation() {
RestrictedTransactionalEventListenerFactory factory = new RestrictedTransactionalEventListenerFactory();
@ -232,6 +239,11 @@ public class TransactionalApplicationListenerMethodAdapterTests {
public void withTransactionalRequiresNewAnnotation(String data) {
}
@TransactionalEventListener
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void withTransactionalNotSupportedAnnotation(String data) {
}
@TransactionalEventListener
@Async @Transactional(propagation = Propagation.REQUIRES_NEW)
public void withAsyncTransactionalAnnotation(String data) {