Spring default behavior for lazy-init
The default behaviour is false:
By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.
I suggest reading up
The lazy-init="default"
setting on a bean only refers to what is set by the default-lazy-init
attribute of the enclosing beans element. The implicit default value of default-lazy-init
is false
.
If there is no lazy-init
attribute specified on a bean, it's always eagerly instantiated.
For those coming here and are using Java config you can set the Bean to lazy-init using annotations like this:
In the configuration class:
@Configuration
// @Lazy - For all Beans to load lazily
public class AppConf {
@Bean
@Lazy
public Demo demo() {
return new Demo();
}
}
For component scanning and auto-wiring:
@Component
@Lazy
public class Demo {
....
....
}
@Component
public class B {
@Autowired
@Lazy // If this is not here, Demo will still get eagerly instantiated to satisfy this request.
private Demo demo;
.......
}