How to schedule a new method in an included Spring web application at runtime?

Right now I have one bean with the @Scheduled method working fine; it is declared in my context.xml application.

<!-- some JPA stuff --> <bean id="aWorkingBean" class="some.package.WorkingBean"> <property name="someDAO" ref="someDAO" /> </bean> <task:annotation-driven scheduler="myScheduler" /> <task:scheduler id="myScheduler" pool-size="10" /> 

What I'm trying to do is programmatically plan another method (e.g. load some annotated class and inject its dependencies) on request. Sort of:

 WebApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext(); BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(NonWorkingBean.class); // add DAO references... ctx.registerBeanDefinition("nonWorkingBean", builder.getBeanDefinition()); // <-- this doesn't work 

Obviously, this does not work because the XmlWebApplicationContext is read-only and does not have a registerBeanDefinition method. Is there any other way to achieve this?

I am using Tomcat 6.0.29 and Spring 3.0.4

+4
source share
2 answers

<task:scheduler> and @Scheduled are just a convenient approach to planning static tasks. This is not suitable for dynamic planning. Yes, you can make it work, but it will be inconvenient.

When you put <task:scheduler id="myScheduler"> in your configuration, Spring creates a TaskScheduler bean called myScheduler . This can be injected into your own beans and can be called programmatically to schedule new tasks. You will need to create a Runnable to go to TaskScheduler , but this should be simple enough.

+3
source

There are several ways to do this, but usually you use AutowireCapableBeanFactory .

Here is one way to do this:

 final WebApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext(); // create the object yourself // and inject the dependenices you want manually final Object existingBean = initializeYourObjectHere(); AutowireCapableBeanFactory beanFactory = ctx.getAutowireCapableBeanFactory(); // now autowire it, injecting the remaining dependencies beanFactory.autowireBeanProperties( existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); // run post processors and register bean under this name beanFactory.initializeBean(existingBean, "newBeanName"); 
0
source

All Articles