Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I lazily register Spring 'bean definitions' in order to improve startup time?

Tags:

java

spring

Our Java Web application loads with over 1000 plugins that are all registered by us as Spring beans using the ApplicationContext#registerBeanDefinition() method. These beans often have other dependencies which we also register as spring beans using the same method (for a total of about 7,000 Spring bean definitions...not including our core application code).

The problem is that the startup time is long (approximately 6.5 minutes of just plugin bean definition loading). We would prefer to spread this load time out over a much longer period while our app is actually processing other requests utilizing plugins that have already had their bean definitions registered. Most of the plugins are seldom used. Thus, we would really like to lazily register our bean definitions (this is different from lazy-init of singleton beans which we already do today). However, this seems costly with any existing Spring ApplicationContext that supports 'hot' refresh() calls (as the Spring documentation refers to it).

The Spring ApplicationContext classes that support 'hot' refresh start by destroying all of the singleton beans. Most of our plugins are singletons, so each call to refresh() would cause most of our plugins to be destroyed and then recreated...costly. If we don't call refresh, then our newly loaded plugin beans will not be post-processed (e.g., AOP, etc...).

We can guarantee that when we are forced to load another plugin, we will also load any of its dependencies that are not already loaded. So, we would never ben in a situation where a loaded bean definition is invalid.

It seems to me that this calls for a new type of Spring ApplicationContext that supports 'hot' refresh, but only for the purpose of adding new bean definitions. Preexisting bean definitions are not removed/reloaded, and not re-processed by BeanFactoryPostProcessors on subsequent refresh() calls, and pre-existing singletons are not destroyed!

Does this already exist?. Is there a better solution that I'm overlooking?

like image 769
Jim Reitz Avatar asked Feb 20 '14 04:02

Jim Reitz


1 Answers

This sounds like you're looking for @Lazy.

4.4.4 Lazy-initialized beans

A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.

like image 125
Markus Malkusch Avatar answered Sep 28 '22 11:09

Markus Malkusch