Support for transactional event listener
Update the application event listener infrastructure to support events that are processed according to a transactional phase. Introduce EventListenerFactory that can be implemented to provide support for additional event listener types. TransactionalEventListener is a new annotation that can be used in lieu of the regular EventListener. Its related factory implementation is registered in the context automatically via @EnableTransactionManagement or <tx:annotation-driven/> By default, a TransactionalEventListener is invoked when the transaction has completed successfully (i.e. AFTER_COMMIT). Additional phases are provided to handle BEFORE_COMMIT and AFTER_ROLLBACK events. If no transaction is running, such listener is not invoked at all unless the `fallbackExecution` flag has been explicitly set. Issue: SPR-12080
This commit is contained in:
@@ -19,11 +19,16 @@ package org.springframework.transaction.annotation;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.ImportAware;
|
||||
import org.springframework.context.annotation.Role;
|
||||
import org.springframework.core.annotation.AnnotationAttributes;
|
||||
import org.springframework.core.type.AnnotationMetadata;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.config.TransactionManagementConfigUtils;
|
||||
import org.springframework.transaction.event.TransactionalEventListenerFactory;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@@ -32,6 +37,7 @@ import org.springframework.util.CollectionUtils;
|
||||
* Spring's annotation-driven transaction management capability.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @author Stephane Nicoll
|
||||
* @since 3.1
|
||||
* @see EnableTransactionManagement
|
||||
*/
|
||||
@@ -46,6 +52,12 @@ public abstract class AbstractTransactionManagementConfiguration implements Impo
|
||||
protected PlatformTransactionManager txManager;
|
||||
|
||||
|
||||
@Bean(name = TransactionManagementConfigUtils.TRANSACTIONAL_EVENT_LISTENER_FACTORY_BEAN_NAME)
|
||||
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
public TransactionalEventListenerFactory transactionalEventListenerFactory() {
|
||||
return new TransactionalEventListenerFactory();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setImportMetadata(AnnotationMetadata importMetadata) {
|
||||
this.enableTx = AnnotationAttributes.fromMap(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2014 the original author or authors.
|
||||
* Copyright 2002-2015 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -26,6 +26,7 @@ import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
|
||||
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||
import org.springframework.beans.factory.xml.BeanDefinitionParser;
|
||||
import org.springframework.beans.factory.xml.ParserContext;
|
||||
import org.springframework.transaction.event.TransactionalEventListenerFactory;
|
||||
import org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor;
|
||||
import org.springframework.transaction.interceptor.TransactionInterceptor;
|
||||
|
||||
@@ -44,6 +45,7 @@ import org.springframework.transaction.interceptor.TransactionInterceptor;
|
||||
* @author Juergen Hoeller
|
||||
* @author Rob Harrop
|
||||
* @author Chris Beams
|
||||
* @author Stephane Nicoll
|
||||
* @since 2.0
|
||||
*/
|
||||
class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
|
||||
@@ -55,6 +57,7 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
|
||||
*/
|
||||
@Override
|
||||
public BeanDefinition parse(Element element, ParserContext parserContext) {
|
||||
registerTransactionalEventListenerFactory(parserContext);
|
||||
String mode = element.getAttribute("mode");
|
||||
if ("aspectj".equals(mode)) {
|
||||
// mode="aspectj"
|
||||
@@ -84,6 +87,13 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
|
||||
TxNamespaceHandler.getTransactionManagerName(element));
|
||||
}
|
||||
|
||||
private void registerTransactionalEventListenerFactory(ParserContext parserContext) {
|
||||
RootBeanDefinition def = new RootBeanDefinition();
|
||||
def.setBeanClass(TransactionalEventListenerFactory.class);
|
||||
parserContext.registerBeanComponent(new BeanComponentDefinition(def,
|
||||
TransactionManagementConfigUtils.TRANSACTIONAL_EVENT_LISTENER_FACTORY_BEAN_NAME));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Inner class to just introduce an AOP framework dependency when actually in proxy mode.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2014 the original author or authors.
|
||||
* Copyright 2002-2015 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -20,6 +20,7 @@ package org.springframework.transaction.config;
|
||||
* Configuration constants for internal sharing across subpackages.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @author Stephane Nicoll
|
||||
* @since 3.1
|
||||
*/
|
||||
public abstract class TransactionManagementConfigUtils {
|
||||
@@ -48,4 +49,10 @@ public abstract class TransactionManagementConfigUtils {
|
||||
public static final String TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME =
|
||||
"org.springframework.transaction.aspectj.AspectJTransactionManagementConfiguration";
|
||||
|
||||
/**
|
||||
* The bean name of the internally managed TransactionalEventListenerFactory.
|
||||
*/
|
||||
public static final String TRANSACTIONAL_EVENT_LISTENER_FACTORY_BEAN_NAME =
|
||||
"org.springframework.transaction.config.internalTransactionalEventListenerFactory";
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
* Copyright 2002-2015 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.transaction.event;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.context.ApplicationEvent;
|
||||
import org.springframework.context.event.ApplicationListenerMethodAdapter;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.context.event.GenericApplicationListener;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* {@link GenericApplicationListener} adapter that delegates the processing of
|
||||
* an event to a {@link TransactionalEventListener} annotated method. Supports
|
||||
* the exact same features as any regular {@link EventListener} annotated method
|
||||
* but is aware of the transactional context of the event publisher.
|
||||
* <p>
|
||||
* Processing of {@link TransactionalEventListener} is enabled automatically when
|
||||
* Spring's transaction management is enabled. For other cases, registering a
|
||||
* bean of type {@link TransactionalEventListenerFactory} is required.
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
* @since 4.2
|
||||
* @see ApplicationListenerMethodAdapter
|
||||
* @see TransactionalEventListener
|
||||
*/
|
||||
class ApplicationListenerMethodTransactionalAdapter extends ApplicationListenerMethodAdapter {
|
||||
|
||||
protected final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private final TransactionalEventListener annotation;
|
||||
|
||||
public ApplicationListenerMethodTransactionalAdapter(String beanName, Class<?> targetClass, Method method) {
|
||||
super(beanName, targetClass, method);
|
||||
this.annotation = findAnnotation(method);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(ApplicationEvent event) {
|
||||
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
TransactionSynchronization transactionSynchronization = createTransactionSynchronization(event);
|
||||
TransactionSynchronizationManager.registerSynchronization(transactionSynchronization);
|
||||
}
|
||||
else if (annotation.fallbackExecution()) {
|
||||
if (annotation.phase() == TransactionPhase.AFTER_ROLLBACK) {
|
||||
logger.warn("Processing '" + event + "' as a fallback execution on AFTER_ROLLBACK phase.");
|
||||
}
|
||||
processEvent(event);
|
||||
}
|
||||
else {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("No transaction is running, skipping '" + event + "' for '" + this + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private TransactionSynchronization createTransactionSynchronization(ApplicationEvent event) {
|
||||
return new TransactionSynchronizationEventAdapter(this, event, this.annotation.phase());
|
||||
}
|
||||
|
||||
static TransactionalEventListener findAnnotation(Method method) {
|
||||
TransactionalEventListener annotation = AnnotationUtils
|
||||
.findAnnotation(method, TransactionalEventListener.class);
|
||||
if (annotation == null) {
|
||||
throw new IllegalStateException("No TransactionalEventListener annotation found ou '" + method + "'");
|
||||
}
|
||||
return annotation;
|
||||
}
|
||||
|
||||
|
||||
private static class TransactionSynchronizationEventAdapter extends TransactionSynchronizationAdapter {
|
||||
|
||||
private final ApplicationListenerMethodAdapter listener;
|
||||
|
||||
private final ApplicationEvent event;
|
||||
|
||||
private final TransactionPhase phase;
|
||||
|
||||
protected TransactionSynchronizationEventAdapter(ApplicationListenerMethodAdapter listener,
|
||||
ApplicationEvent event, TransactionPhase phase) {
|
||||
|
||||
this.listener = listener;
|
||||
this.event = event;
|
||||
this.phase = phase;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeCommit(boolean readOnly) {
|
||||
if (phase == TransactionPhase.BEFORE_COMMIT) {
|
||||
processEvent();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(int status) {
|
||||
if (phase == TransactionPhase.AFTER_COMPLETION) {
|
||||
processEvent();
|
||||
}
|
||||
else if (phase == TransactionPhase.AFTER_COMMIT && status == STATUS_COMMITTED) {
|
||||
processEvent();
|
||||
}
|
||||
else if (phase == TransactionPhase.AFTER_ROLLBACK && status == STATUS_ROLLED_BACK) {
|
||||
processEvent();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return this.listener.getOrder();
|
||||
}
|
||||
|
||||
protected void processEvent() {
|
||||
this.listener.processEvent(this.event);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Copyright 2002-2015 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.transaction.event;
|
||||
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
|
||||
/**
|
||||
* The phase at which a transactional event listener applies.
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
* @since 4.2
|
||||
* @see TransactionalEventListener
|
||||
*/
|
||||
public enum TransactionPhase {
|
||||
|
||||
/**
|
||||
* Fire the event before transaction commit.
|
||||
* @see TransactionSynchronization#beforeCommit(boolean)
|
||||
*/
|
||||
BEFORE_COMMIT,
|
||||
|
||||
/**
|
||||
* Fire the event after the transaction has completed. For
|
||||
* more fine-grained event, use {@link #AFTER_COMMIT} or
|
||||
* {@link #AFTER_ROLLBACK} to intercept transaction commit
|
||||
* or rollback respectively.
|
||||
* @see TransactionSynchronization#afterCompletion(int)
|
||||
*/
|
||||
AFTER_COMPLETION,
|
||||
|
||||
/**
|
||||
* Fire the event after the commit has completed successfully.
|
||||
* @see TransactionSynchronization#afterCompletion(int)
|
||||
* @see TransactionSynchronization#STATUS_COMMITTED
|
||||
*/
|
||||
AFTER_COMMIT,
|
||||
|
||||
/**
|
||||
* Fire the event if the transaction has rolled back.
|
||||
* @see TransactionSynchronization#afterCompletion(int)
|
||||
* @see TransactionSynchronization#STATUS_ROLLED_BACK
|
||||
*/
|
||||
AFTER_ROLLBACK
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright 2002-2015 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.transaction.event;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.springframework.context.event.EventListener;
|
||||
|
||||
/**
|
||||
* An {@link EventListener} that is invoked according to a {@link TransactionPhase}.
|
||||
* <p>
|
||||
* If the event is not published in the boundaries of a managed transaction, the event
|
||||
* is discarded unless the {@link #fallbackExecution()} flag is explicitly set. If a
|
||||
* transaction is running, the event is processed according to its {@link TransactionPhase}.
|
||||
* <p>
|
||||
* Adding {@link org.springframework.core.annotation.Order @Order} on your annotated method
|
||||
* allows you to prioritize that listener amongst other listeners running on the same phase.
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
* @since 4.2
|
||||
*/
|
||||
@EventListener
|
||||
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface TransactionalEventListener {
|
||||
|
||||
/**
|
||||
* Phase to bind the handling of an event to. If no transaction is in progress, the
|
||||
* event is not processed at all unless {@link #fallbackExecution()} has been
|
||||
* enabled explicitly.
|
||||
*/
|
||||
TransactionPhase phase() default TransactionPhase.AFTER_COMMIT;
|
||||
|
||||
/**
|
||||
* Specify if the event should be processed if no transaction is running.
|
||||
*/
|
||||
boolean fallbackExecution() default false;
|
||||
|
||||
/**
|
||||
* Spring Expression Language (SpEL) attribute used for conditioning the event handling.
|
||||
* <p>Default is "", meaning the event is always handled.
|
||||
* @see EventListener#condition()
|
||||
*/
|
||||
String condition() default "";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Copyright 2002-2015 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.transaction.event;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.context.event.EventListenerFactory;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
|
||||
/**
|
||||
* {@link EventListenerFactory} implementation that handles {@link TransactionalEventListener}
|
||||
* annotated method.
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
* @since 4.2
|
||||
*/
|
||||
public class TransactionalEventListenerFactory implements EventListenerFactory, Ordered {
|
||||
|
||||
private int order = 50;
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public void setOrder(int order) {
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsMethod(Method method) {
|
||||
return AnnotationUtils.findAnnotation(method, TransactionalEventListener.class) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationListener<?> createApplicationListener(String beanName, Class<?> type, Method method) {
|
||||
return new ApplicationListenerMethodTransactionalAdapter(beanName, type, method);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user