title: Spring lazy loading - loading one bean loads all @Lazy beans of that class
body: <p>I've declared two beans of same class type. Initialized them to be <code>@Lazy</code>. <code>@Autowiring</code> one bean of them automatically initialized the other bean as well. I was surprised to see that behavior. Just curious to know more about the mechanism.</p>
  
  <p>Code</p>
  
  <pre><code>//bean
  public class HelloWorld {
      public HelloWorld(String msg){
           System.out.println( msg + ", " + this);
      }   
  }
  
  @Configuration
  @Lazy
  public class SpringAppContext {
  
       @Bean(name="helloworld1")
       public HelloWorld helloworld1(){
          return new HelloWorld("helloworld1");
       }  
       @Bean(name="helloworld2")
       public HelloWorld helloworld2(){
          return new HelloWorld("helloworld2");
       }
  }
  
  @RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration(classes={SpringAppContext.class})
  public class SpringBeanLazyLoadTest {
       @Autowired
       private HelloWorld helloworld2;
  
       @Test // this test is lame but just trying out.
       public void print(){
          System.out.println("Autowired: " + helloworld2);
       }
  }
  </code></pre>
  
  <p>Output</p>
  
  <pre><code>helloworld2, my.entp.spring.HelloWorld@3a9bba
  helloworld1, my.entp.spring.HelloWorld@163f7a1 // why was helloworld1 initialized?
  Autowired: my.entp.spring.HelloWorld@3a9bba
  </code></pre>
  
  <p>If you observe the output, you may notice that the <code>helloworld1</code> bean is initialized when <code>helloworld2</code> is <code>@Autowired</code>. </p>
  
  <p>I tested by removing <code>@Autowired</code> and it produced expected results: initialized none of the beans.</p>