Hi all,
I want to create some spring beans after startup in a factory-ish pattern. For example every so often I have some work to do and I need to create a task bean (which probably has dependents on other singleton spring beans) and execute it.
There may be several pieces of work to execute concurrently so each task bean needs to be independent (prototype).
Is there any common pattern people use to achieve this?
As I see it I need to interact with the container/applicationContext somehow but I don't really want to scatter injections of applicationContext/beanFactory and calls to getBean("...") everywhere.
I thought of something like this (note the "factory" is something I'm imagining, rather than something that exists)
<bean id="myTask" class="MyTask" scope="prototype">
<property name="entityManager" ref=".../>
...
</bean>
<bean id="myTaskExecutor" class="MyTaskExecutor">
<property name="taskFactory">
<xxx:factory bean="myTask"/>
</property>
</bean>
And then code
class MyTaskExecutor
{
private Factory<MyTask> taskFactory;
public void setTaskFactory( Factory<MyTask> taskFactory )
{
this.taskFactory = taskFactory;
}
}
And maybe an annotation version
class MyTaskExecutor
{
@Factory(MyTask.class)
private Factory<MyTask> taskFactory;
}
Maybe there's something like the above already? Or am I missing something fundamental somewhere.
I realise I could have a singleton MyTaskFactory and use that to instantiate using "new" but then I'd have to pass all of it's dependents from the factory which feels wrong.
So I guess to sum up the question is
What is the recommended way of creating prototype spring beans on-demand from within application code?
Appreciate any input.