Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SmartInitializingSingleton vs InitializingBean in Spring

Tags:

java

spring

For a long time spring-beans had an InitializingBean interface that developers could use to specify the custom logic that is performed once beans properties have been set by BeanFactory. However, starting from Spring 4.1, we have another interface in spring-beans jar, called SmartInitializingSingleton. In the javadoc of the SmartInitializingSingleton we can find:

Callback interface triggered at the end of the singleton pre-instantiation phase during {@link BeanFactory} bootstrap.

But that is unclear to me what is the "pre-instantiation phase" and how SmartInitializingSingleton differs from the old InitializingBean. Can anyone please explain this?

like image 626
misha2048 Avatar asked Nov 29 '25 17:11

misha2048


1 Answers

The main difference between the two is the time at which point in time it gets called.
While InitializingBean gets called in the post-processing phase while instantiating the current singleton bean, SmartInitializingSingleton gets called after ALL singleton beans have been initialized and instantiated.

While I agree the description of the interface may cause confusion, the method summary of both interfaces are actually very clear.

InitializingBean
afterPropertiesSet() : Invoked by the containing BeanFactory after it has set all bean properties and satisfied BeanFactoryAware, ApplicationContextAware etc.

SmartInitializingSingleton
afterSingletonsInstantiated() : Invoked right at the end of the singleton pre-instantiation phase, with a guarantee that all regular singleton beans have been created already.

Obviously, the benefit of the latter is that you can use any of your applications Singleton Beans in your initialization logic with the guarantee that they have all been instantiated and are all ready to use.

The pre-instantiation phase in Spring is the phase where Spring eagerly creates and initializes singleton beans, in contrast to beans with other scopes.

like image 77
Nico Van Belle Avatar answered Dec 01 '25 07:12

Nico Van Belle