1
<bean id="applicationEventMulticaster"
        class="com.test.listener.CustomApplicationEventMulticaster">
        <property name="taskExecutor" >
            <bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
                <property name="maxPoolSize" value="10"/>
                <property name="corePoolSize" value="10"/>
                <property name="waitForTasksToCompleteOnShutdown" value="true"/>
                <property name="awaitTerminationSeconds" value="200"/>
            </bean>
        </property>
    </bean>


public class CustomApplicationEventMulticaster extends SimpleApplicationEventMulticaster {
    
    @Override
    public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
        
            boolean async = (event instanceof AbstractApplicationEvent) ? ((AbstractApplicationEvent) event).isAsyncEvent()
                    : true;
            final SecurityContext sc = SecurityContextHolder.getContext();
            ResolvableType defaultEventType = ResolvableType.forInstance(event);
            for (final ApplicationListener listener : getApplicationListeners(event, defaultEventType)) {
                Executor executor = getTaskExecutor();
                if (async && executor != null) {
                    executor.execute(() -> {
                            try {
                                SecurityContextHolder.setContext(sc);
                                listener.onApplicationEvent(event);
                            } finally {
                                SecurityContextHolder.clearContext();
                            }
                    });
                } else {
                    listener.onApplicationEvent(event);
                }
            }
        
    }

}

在应用程序中,我试图触发同步和异步事件。

这样做很好吗?

4

1 回答 1

0
executor.execute(() -> {
                            try {
                                SecurityContext emptyContext = SecurityContextHolder.createEmptyContext();
                                emptyContext.setAuthentication(sc.getAuthentication());
                                listener.onApplicationEvent(event);
                            } finally {
                                SecurityContextHolder.clearContext();
                            }
                        });
于 2020-07-15T16:00:04.567 回答