Dattatreya Kugve
Dattatreya Kugve

Reputation: 377

Alternate for ScheduledExecutorFactoryBean in Spring 4

We upgraded spring version of our project from 3.2.7 to 4.0.6 and found that org.springframework.scheduling.timer.TimerFactoryBean class is no more exists spring 4.0.6. I tried the solution mentioned here stackOverflowSolution . But it is not working for me.

Here is what i tried. In one of context xml I had following bean

<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list> <!-- leave empty --> </list> </property> </bean>

As per solution mentioned in the link I changed the bean definition like below to use org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean

<bean id="timerFactory" class="org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean">

    <!-- <property name="scheduledTimerTasks"> -->
    <property name="scheduledExecutorTasks">

        <list>
            <!-- leave empty-->
        </list> 
    </property> 
</bean> 

But this solution is not working for me because Following code is breaking because of type cast

  ProcessInitiatorTask timerTask = (ProcessInitiatorTask) context.getBean("initiateProcessesTask", ProcessInitiatorTask.class);
            event.getServletContext().setAttribute("CURRENT_TASK", timerTask);

            timerTask.init(config);

            // Code will break at below line
            Timer timer = (Timer) context.getBean("timerFactory", Timer.class);   
            timer.schedule(timerTask, 10000L, config.getPeriod().longValue() * 60 * 1000); 

When I run this code I am getting org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'timerFactory' must be of type [java.util.Timer], but was actually of type [java.util.concurrent.ScheduledThreadPoolExecutor]

Please let me know what modifications I need to make to make this code work with Spring 4

Upvotes: 1

Views: 2341

Answers (1)

Dattatreya Kugve
Dattatreya Kugve

Reputation: 377

Got it working. In bean declaration timerFactory bean was declared as of type org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean, but I was trying to cast it to java.util.Timer which was wrong in first place. Then I tried to cast it to ScheduledExecutorFactoryBean which still didn't work. This is because ScheduledExecutorFactoryBean is a Spring Factory bean. Which means that it is meant to create an object of a target type but not an instance of itself. In this case target type for ScheduledExecutorFactoryBean isorg.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean So I casted timerFactory bean to type ScheduledExecutorFactoryBean which worked. Following is the modified line of code

 ScheduledThreadPoolExecutor timer = 
       (ScheduledThreadPoolExecutor) context.getBean("timerFactory",
       ScheduledThreadPoolExecutor.class);

Upvotes: 1

Related Questions