Lazy initialization
By default, when a Spring web application starts up, all of the defined beans are instantiated automatically. If you have a huge application with thousands of beans, this could take a considerable amount of time.
One idea to speed up the application startup could be to set the loading of beans to lazy. That means, that most beans won’t be created at the application startup. They will be created when they are required for the first time by some other code. If you are using XML configuration you can tell Spring to initialize all beans lazily by default using the default-lazy-init
attribute:
<beans xmlns="..." xmlns:xsi="..." xsi:schemaLocation="..." default-lazy-init="true"> ... </beans>
Why it may not work?
In theory, this could work, and save us some time during the startup process. In reality however, it is possible that despite our efforts to use lazy loading, almost all beans are created at the time of startup. Let’s see why.
I mentioned earlier that lazy loading means that beans are only created when they are first required. But what if almost all beans are required at the time of application startup?
In a Spring web application controllers are responsibe for serving incoming requests. The controllers are also Spring beans, and their methods are annotated with the routes they are mapped to. So in order to know which Controller and which method to call when a request comes in, all controllers must be instantiated during application startup.
These are just the controllers yet, but they start a “chain reaction”. Controllers require services to do their job, so the services will also get instantiated and injected into the controllers. These services probably require some kind of repositories to get data from a database. So when a service is instantiated, the referenced repositories are also created. And due to this chain reaction, we will quite surely reach the majority of the beans present in a web application. At the end of the process we have an instance of most of the beans as if we didn’t use lazy initialization.
When could it work?
If you have beans in your application that are not required directly or indirectly by beans that are created on startup, then you could benefit from lazy initialization.
This can happen for example when you are running a test case without your controllers. In this situation it is possible that almost no beans are created when the application starts up. Other possibility is if you have some kind of factories in your code that create beans based on a condition. If the condition is not met for some of your beans, they may not get created until later time.