title: How to create a request scoped bean at runtime with spring
body: <p>I have a spring application and want to create a bean at runtime per request to inject it into another class, just like <code>@Producer</code> for CDI.</p>
  
  <p>My bean is just a simple POJO:</p>
  
  <pre><code>public class UserDetails {
  
      private String name;
  
      // getter / setter ... 
  
      public UserDetails(String name) {
          this.name = name;
      }
  }
  </code></pre>
  
  <p>My producer class looks like this:</p>
  
  <pre><code>@Configuration
  public class UserFactory {
  
      @Bean
      @Scope("request")
      public UserDetails createUserDetails() {
          // this method should be called on every request
          String name = SecurityContextHolder.getContext()
                          .getAuthentication().getPrincipal(); // get some user details, just an example (I am aware of Principal)
  
          // construct a complex user details object here
          return new UserDetails(name)
      }
  }
  </code></pre>
  
  <p>And this is the class where the <code>UserDetails</code> instance should be injected:</p>
  
  <pre><code>@RestController
  @RequestMapping(value = "/api/something")
  public class MyResource {
  
      @RequestMapping(method = RequestMethod.GET)
      @ResponseBody
      public List&lt;String&gt; getSomething(UserDetails userDetails) {
          // the userdetails should be injected here per request, some annotations missing?
  
          // do something
      }
  }
  </code></pre>
  
  <p>The problem is that Spring complains at runtime about no default constructor (of course).</p>
  
  <p><code>Failed to instantiate [UserDetails]: No default constructor found</code></p>
  
  <p>But this is intended and I want to call my own factory to let it handle the Instantiation.</p>
  
  <p>How can I achieve this? Why is <code>UserFactory</code> never called?</p>