spring的TransactionalEventListener事務(wù)感知源碼解析
序
本文主要研究一下spring的TransactionalEventListener
TransactionalEventListener
org/springframework/transaction/event/TransactionalEventListener.java
/**
* An {@link EventListener} that is invoked according to a {@link TransactionPhase}.
*
* <p>If the event is not published within an active 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 {@code TransactionPhase}.
*
* <p>Adding {@link org.springframework.core.annotation.Order @Order} to your annotated
* method allows you to prioritize that listener amongst other listeners running before
* or after transaction completion.
*
* @author Stephane Nicoll
* @author Sam Brannen
* @since 4.2
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EventListener
public @interface TransactionalEventListener {
/**
* Phase to bind the handling of an event to.
* <p>The default phase is {@link TransactionPhase#AFTER_COMMIT}.
* <p>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;
/**
* Whether the event should be processed if no transaction is running.
*/
boolean fallbackExecution() default false;
/**
* Alias for {@link #classes}.
*/
@AliasFor(annotation = EventListener.class, attribute = "classes")
Class<?>[] value() default {};
/**
* The event classes that this listener handles.
* <p>If this attribute is specified with a single value, the annotated
* method may optionally accept a single parameter. However, if this
* attribute is specified with multiple values, the annotated method
* must <em>not</em> declare any parameters.
*/
@AliasFor(annotation = EventListener.class, attribute = "classes")
Class<?>[] classes() default {};
/**
* Spring Expression Language (SpEL) attribute used for making the event
* handling conditional.
* <p>The default is {@code ""}, meaning the event is always handled.
* @see EventListener#condition
*/
String condition() default "";
}TransactionalEventListener是EventListener的事務(wù)感知版本,默認(rèn)的是TransactionPhase是AFTER_COMMIT
ApplicationListenerMethodTransactionalAdapter
org/springframework/transaction/event/ApplicationListenerMethodTransactionalAdapter.java
/**
* {@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
* @author Juergen Hoeller
* @since 4.2
* @see ApplicationListenerMethodAdapter
* @see TransactionalEventListener
*/
class ApplicationListenerMethodTransactionalAdapter extends ApplicationListenerMethodAdapter {
private final TransactionalEventListener annotation;
public ApplicationListenerMethodTransactionalAdapter(String beanName, Class<?> targetClass, Method method) {
super(beanName, targetClass, method);
TransactionalEventListener ann = AnnotatedElementUtils.findMergedAnnotation(method, TransactionalEventListener.class);
if (ann == null) {
throw new IllegalStateException("No TransactionalEventListener annotation found on method: " + method);
}
this.annotation = ann;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (TransactionSynchronizationManager.isSynchronizationActive()
&& TransactionSynchronizationManager.isActualTransactionActive()) {
TransactionSynchronization transactionSynchronization = createTransactionSynchronization(event);
TransactionSynchronizationManager.registerSynchronization(transactionSynchronization);
}
else if (this.annotation.fallbackExecution()) {
if (this.annotation.phase() == TransactionPhase.AFTER_ROLLBACK && logger.isWarnEnabled()) {
logger.warn("Processing " + event + " as a fallback execution on AFTER_ROLLBACK phase");
}
processEvent(event);
}
else {
// No transactional event execution at all
if (logger.isDebugEnabled()) {
logger.debug("No transaction is active - skipping " + event);
}
}
}
private TransactionSynchronization createTransactionSynchronization(ApplicationEvent event) {
return new TransactionSynchronizationEventAdapter(this, event, this.annotation.phase());
}
private static class TransactionSynchronizationEventAdapter extends TransactionSynchronizationAdapter {
private final ApplicationListenerMethodAdapter listener;
private final ApplicationEvent event;
private final TransactionPhase phase;
public TransactionSynchronizationEventAdapter(ApplicationListenerMethodAdapter listener,
ApplicationEvent event, TransactionPhase phase) {
this.listener = listener;
this.event = event;
this.phase = phase;
}
@Override
public int getOrder() {
return this.listener.getOrder();
}
@Override
public void beforeCommit(boolean readOnly) {
if (this.phase == TransactionPhase.BEFORE_COMMIT) {
processEvent();
}
}
@Override
public void afterCompletion(int status) {
if (this.phase == TransactionPhase.AFTER_COMMIT && status == STATUS_COMMITTED) {
processEvent();
}
else if (this.phase == TransactionPhase.AFTER_ROLLBACK && status == STATUS_ROLLED_BACK) {
processEvent();
}
else if (this.phase == TransactionPhase.AFTER_COMPLETION) {
processEvent();
}
}
protected void processEvent() {
this.listener.processEvent(this.event);
}
}
}ApplicationListenerMethodTransactionalAdapter繼承了ApplicationListenerMethodAdapter,它的構(gòu)造器會(huì)找到指定方法的TransactionalEventListener信息;其onApplicationEvent方法在有事務(wù)的時(shí)候會(huì)創(chuàng)建并注冊(cè)transactionSynchronization到當(dāng)前事務(wù),沒(méi)有事務(wù)若允許fallbackExecution也會(huì)執(zhí)行processEvent
TransactionSynchronizationEventAdapter只是覆蓋了beforeCommit及afterCompletion兩個(gè)方法,在afterCompletion方法中根據(jù)status的值與phase的值的匹配關(guān)系決定是否執(zhí)行processEvent
TransactionalEventListenerFactory
org/springframework/transaction/event/TransactionalEventListenerFactory.java
/**
* {@link EventListenerFactory} implementation that handles {@link TransactionalEventListener}
* annotated methods.
*
* @author Stephane Nicoll
* @since 4.2
*/
public class TransactionalEventListenerFactory implements EventListenerFactory, Ordered {
private int order = 50;
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
@Override
public boolean supportsMethod(Method method) {
return AnnotatedElementUtils.hasAnnotation(method, TransactionalEventListener.class);
}
@Override
public ApplicationListener<?> createApplicationListener(String beanName, Class<?> type, Method method) {
return new ApplicationListenerMethodTransactionalAdapter(beanName, type, method);
}
}TransactionalEventListenerFactory用于創(chuàng)建ApplicationListenerMethodTransactionalAdapter
EventListenerMethodProcessor
org/springframework/context/event/EventListenerMethodProcessor.java
public class EventListenerMethodProcessor
implements SmartInitializingSingleton, ApplicationContextAware, BeanFactoryPostProcessor {
//......
@Override
public void afterSingletonsInstantiated() {
ConfigurableListableBeanFactory beanFactory = this.beanFactory;
Assert.state(this.beanFactory != null, "No ConfigurableListableBeanFactory set");
String[] beanNames = beanFactory.getBeanNamesForType(Object.class);
for (String beanName : beanNames) {
if (!ScopedProxyUtils.isScopedTarget(beanName)) {
Class<?> type = null;
try {
type = AutoProxyUtils.determineTargetClass(beanFactory, beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
}
}
if (type != null) {
if (ScopedObject.class.isAssignableFrom(type)) {
try {
Class<?> targetClass = AutoProxyUtils.determineTargetClass(
beanFactory, ScopedProxyUtils.getTargetBeanName(beanName));
if (targetClass != null) {
type = targetClass;
}
}
catch (Throwable ex) {
// An invalid scoped proxy arrangement - let's ignore it.
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve target bean for scoped proxy '" + beanName + "'", ex);
}
}
}
try {
processBean(beanName, type);
}
catch (Throwable ex) {
throw new BeanInitializationException("Failed to process @EventListener " +
"annotation on bean with name '" + beanName + "'", ex);
}
}
}
}
}
private void processBean(final String beanName, final Class<?> targetType) {
if (!this.nonAnnotatedClasses.contains(targetType) &&
AnnotationUtils.isCandidateClass(targetType, EventListener.class) &&
!isSpringContainerClass(targetType)) {
Map<Method, EventListener> annotatedMethods = null;
try {
annotatedMethods = MethodIntrospector.selectMethods(targetType,
(MethodIntrospector.MetadataLookup<EventListener>) method ->
AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class));
}
catch (Throwable ex) {
// An unresolvable type in a method signature, probably from a lazy bean - let's ignore it.
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve methods for bean with name '" + beanName + "'", ex);
}
}
if (CollectionUtils.isEmpty(annotatedMethods)) {
this.nonAnnotatedClasses.add(targetType);
if (logger.isTraceEnabled()) {
logger.trace("No @EventListener annotations found on bean class: " + targetType.getName());
}
}
else {
// Non-empty set of methods
ConfigurableApplicationContext context = this.applicationContext;
Assert.state(context != null, "No ApplicationContext set");
List<EventListenerFactory> factories = this.eventListenerFactories;
Assert.state(factories != null, "EventListenerFactory List not initialized");
for (Method method : annotatedMethods.keySet()) {
for (EventListenerFactory factory : factories) {
if (factory.supportsMethod(method)) {
Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName));
ApplicationListener<?> applicationListener =
factory.createApplicationListener(beanName, targetType, methodToUse);
if (applicationListener instanceof ApplicationListenerMethodAdapter) {
((ApplicationListenerMethodAdapter) applicationListener).init(context, this.evaluator);
}
context.addApplicationListener(applicationListener);
break;
}
}
}
if (logger.isDebugEnabled()) {
logger.debug(annotatedMethods.size() + " @EventListener methods processed on bean '" +
beanName + "': " + annotatedMethods);
}
}
}
}
//......
}EventListenerMethodProcessor實(shí)現(xiàn)了SmartInitializingSingleton接口,其afterSingletonsInstantiated方法先確定type,然后執(zhí)行processBean,該方法會(huì)先收集annotatedMethods,然后遍歷該方法,在遍歷factories針對(duì)支持該方法的factory執(zhí)行createApplicationListener,添加到context中
小結(jié)
TransactionalEventListener是EventListener的事務(wù)感知版本,默認(rèn)的是TransactionPhase是AFTER_COMMIT,TransactionSynchronizationEventAdapter只是覆蓋了beforeCommit及afterCompletion兩個(gè)方法,在afterCompletion方法中根據(jù)status的值與phase的值的匹配關(guān)系決定是否執(zhí)行processEvent,因而這里拋出的異常會(huì)被捕獲并log下來(lái)
doc
以上就是spring的TransactionalEventListener源碼解析的詳細(xì)內(nèi)容,更多關(guān)于spring TransactionalEventListener的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
如何利用postman完成JSON串的發(fā)送功能(springboot)
這篇文章主要介紹了如何利用postman完成JSON串的發(fā)送功能(springboot),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
解決maven clean報(bào)錯(cuò):Failed to delete xxxxx\t
這篇文章主要介紹了解決maven clean報(bào)錯(cuò):Failed to delete xxxxx\target\xxxx.jar問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
JavaFX實(shí)現(xiàn)簡(jiǎn)單日歷效果
這篇文章主要為大家詳細(xì)介紹了JavaFX實(shí)現(xiàn)簡(jiǎn)單日歷效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11
使用socket實(shí)現(xiàn)網(wǎng)絡(luò)聊天室和私聊功能
這篇文章主要介紹了使用socket實(shí)現(xiàn)網(wǎng)絡(luò)聊天室和私聊功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12
PowerJobAutoConfiguration自動(dòng)配置源碼流程解析
這篇文章主要為大家介紹了PowerJobAutoConfiguration自動(dòng)配置源碼流程解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
Java使用POI實(shí)現(xiàn)excel文件的導(dǎo)入和導(dǎo)出
這篇文章主要為大家詳細(xì)介紹了Java如何使用POI實(shí)現(xiàn)excel文件的導(dǎo)入和導(dǎo)出功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12
Java中PriorityQueue實(shí)現(xiàn)最小堆和最大堆的用法
很多時(shí)候都會(huì)遇到PriorityQueue,本文主要介紹了Java中PriorityQueue實(shí)現(xiàn)最小堆和最大堆的用法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06
SpringBoot + Mybatis Plus 整合 Redis的
文章詳細(xì)介紹了Redis在用戶管理系統(tǒng)中的應(yīng)用,包括用戶信息緩存、Token存儲(chǔ)、接口限流、重復(fù)提交攔截和熱點(diǎn)數(shù)據(jù)預(yù)加載等場(chǎng)景,并提供了具體的實(shí)現(xiàn)方案和步驟,感興趣的朋友一起看看吧2025-03-03

