title: How to make Spring beans thread-safe
body: <p>As far as I know, Spring beans are singleton by default.</p>
  
  <p>What I want is make beans thread-safe considering instance attributes.
  I'll try to show you using a simple example.<br>
  Consider the following code:</p>
  
  <pre><code>@Controller
  public class MyServlet {
  
      @Autowired
      private HelloService service;
  
      @RequestMapping(value="/hello", method = RequestMethod.GET)
      public void sayHello(HttpServletRequest req, HttpServletResponse res) throws IOException {
          service.doStuff();
      }
  
  }
  
  
  public class HelloService {
  
      private int i = 1;
  
      public void doStuff() {
          System.out.println("Started " + i);
          i++;
          System.out.println(Thread.currentThread().getName() + " Done " + i);
      }
  }
  </code></pre>
  
  <p>The output will be something like this:</p>
  
  <pre><code>32911580@qtp-28064776-0 - Started 1
  7802158@qtp-28064776-2 - Started 2
  32911580@qtp-28064776-0 - Done 3
  7802158@qtp-28064776-2 - Done 3
  </code></pre>
  
  <p>This prove the "i" var is shared between multiple threads.</p>
  
  <p>I've also tryed to define the HelloService bean as prototype, like this</p>
  
  <pre><code>&lt;bean id="helloService" class="my.package.HelloService" scope="prototype" /&gt;
  </code></pre>
  
  <p>but the result is the same.</p>
  
  <p>The only ways I found to solve this are:
  - move the declaration into doStuff() method, but it's not what I want
  - make the doStuff() method, but this means have locks</p>
  
  <p>What I would like is have a new instance of HelloService on every call.</p>
  
  <p>Can anyone help me?
  Thanks in advance.</p>
  
  <h2>Update</h2>
  
  <p>I found the solution with method injection using lookup-method.
  <a href="http://static.springsource.org/spring/docs/3.1.1.RELEASE/spring-framework-reference/html/beans.html#beans-factory-lookup-method-injection" rel="nofollow">http://static.springsource.org/spring/docs/3.1.1.RELEASE/spring-framework-reference/html/beans.html#beans-factory-lookup-method-injection</a></p>