I've declared two beans of same class type. Initialized them to be @Lazy
. @Autowiring
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.
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);
}
}
Output
helloworld2, my.entp.spring.HelloWorld@3a9bba
helloworld1, my.entp.spring.HelloWorld@163f7a1 // why was helloworld1 initialized?
Autowired: my.entp.spring.HelloWorld@3a9bba
If you observe the output, you may notice that the helloworld1
bean is initialized when helloworld2
is @Autowired
.
I tested by removing @Autowired
and it produced expected results: initialized none of the beans.