title: Spring Java Config: how do you create a prototype-scoped @Bean with runtime arguments?
body: <p>Using Spring's Java Config, I need to acquire/instantiate a prototype-scoped bean with constructor arguments that are only obtainable at runtime.  Consider the following code example (simplified for brevity):</p>
  
  <pre><code>@Autowired
  private ApplicationContext appCtx;
  
  public void onRequest(Request request) {
      //request is already validated
      String name = request.getParameter("name");
      Thing thing = appCtx.getBean(Thing.class, name);
  
      //System.out.println(thing.getName()); //prints name
  }
  </code></pre>
  
  <p>where the Thing class is defined as follows:</p>
  
  <pre><code>public class Thing {
  
      private final String name;
  
      @Autowired
      private SomeComponent someComponent;
  
      @Autowired
      private AnotherComponent anotherComponent;
  
      public Thing(String name) {
          this.name = name;
      }
  
      public String getName() {
          return this.name;
      }
  }
  </code></pre>
  
  <p>Notice <code>name</code> is <code>final</code>: it can only be supplied via a constructor, and guarantees immutability.  The other dependencies are implementation-specific dependencies of the <code>Thing</code> class, and shouldn't be known to (tightly coupled to) the request handler implementation.</p>
  
  <p>This code works perfectly well with Spring XML config, for example:</p>
  
  <pre><code>&lt;bean id="thing", class="com.whatever.Thing" scope="prototype"&gt;
      &lt;!-- other post-instantiation properties omitted --&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>How do I achieve the same thing with Java config?  The following does not work using Spring 3.x:</p>
  
  <pre><code>@Bean
  @Scope("prototype")
  public Thing thing(String name) {
      return new Thing(name);
  }
  </code></pre>
  
  <p>Now, I <em>could</em> create a Factory, e.g.:</p>
  
  <pre><code>public interface ThingFactory {
      public Thing createThing(String name);
  }
  </code></pre>
  
  <p>But that <em>defeats the entire point of using Spring to replace the ServiceLocator and Factory design pattern</em>, which would be ideal for this use case.</p>
  
  <p>If Spring Java Config could do this, I would be able to avoid:</p>
  
  <ul>
  <li>defining a Factory interface</li>
  <li>defining a Factory implementation</li>
  <li>writing tests for the Factory implementation</li>
  </ul>
  
  <p>That's a ton of work (relatively speaking) for something so trivial that Spring already supports via XML config.</p>