title: Creating beans on-demand using spring
body: <p>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.</p>
  
  <p>There may be several pieces of work to execute concurrently so each task bean needs to be independent (prototype).</p>
  
  <p>Is there any common pattern people use to achieve this?</p>
  
  <p>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.</p>
  
  <p>I thought of something like this (note the "factory" is something I'm imagining, rather than something that exists)</p>
  
  <pre><code>&lt;bean id="myTask" class="MyTask" scope="prototype"&gt;
    &lt;property name="entityManager" ref=".../&gt;
    ...
  &lt;/bean&gt;
  
  &lt;bean id="myTaskExecutor" class="MyTaskExecutor"&gt;
    &lt;property name="taskFactory"&gt;
       &lt;xxx:factory bean="myTask"/&gt;
    &lt;/property&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>And then code</p>
  
  <pre><code>class MyTaskExecutor
  {
    private Factory&lt;MyTask&gt; taskFactory;
  
    public void setTaskFactory( Factory&lt;MyTask&gt; taskFactory )
    {
      this.taskFactory = taskFactory;
    }
  }
  </code></pre>
  
  <p>And maybe an annotation version</p>
  
  <pre><code>class MyTaskExecutor
  {
    @Factory(MyTask.class)
    private Factory&lt;MyTask&gt; taskFactory;
  
  }
  </code></pre>
  
  <p>Maybe there's something like the above already?  Or am I missing something fundamental somewhere.</p>
  
  <p>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.</p>
  
  <p>So I guess to sum up the question is</p>
  
  <p><strong>What is the recommended way of creating prototype spring beans on-demand from within application code?</strong></p>
  
  <p>Appreciate any input.</p>