How to configure Async and Sync Event publishers using spring

前端 未结 4 877
北恋
北恋 2021-01-17 13:25

I am trying to implement an event framework using spring events.I came to know that the default behavior of spring event framework is sync. But during spring context initial

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-17 14:07

    no, you can't do that, the spring initApplicationEventMulticaster just init only one, and the BeanName must be applicationEventMulticaster. so you just can choose one of below Executor:

    - org.springframework.core.task.SyncTaskExecutor

    - org.springframework.core.task.SimpleAsyncTaskExecutor

    - your own Executor: org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor

    any way, you can modify org.springframework.context.event.SimpleApplicationEventMulticaster to add your logic, then you can control whether need to Sync/Async

        /**
     * Initialize the ApplicationEventMulticaster.
     * Uses SimpleApplicationEventMulticaster if none defined in the context.
     * @see org.springframework.context.event.SimpleApplicationEventMulticaster
     */
    protected void initApplicationEventMulticaster() {
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
            this.applicationEventMulticaster =
                    beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
            if (logger.isDebugEnabled()) {
                logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
            }
        }
        else {
            this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
            beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
                        APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
                        "': using default [" + this.applicationEventMulticaster + "]");
            }
        }
    }
    

提交回复
热议问题