How to create a singleton bean when starting a Spring application?
sobes.tech AI
Answer from AI
By default, singleton beans in Spring are created upon the first request to them (lazy loading). To create a singleton bean at application startup (eager loading), you can use the following approaches:
-
Use the
@Lazy(false)annotation:// Bean class @Component @Lazy(false) // Indicates that the bean is NOT lazy, i.e., created at context startup public class EagerSingletonBean { // ... bean implementation }This is the most explicit way to specify that a particular bean should be initialized at Spring context startup.
@Lazy(false)at the bean class level overrides any global or default lazy loading behavior. -
Configuration via XML:
In Spring's XML configuration, you can explicitly specify
lazy-init="false"for bean definition:<bean id="eagerSingletonBean" class="com.example.EagerSingletonBean" lazy-init="false"/>This attribute controls the initialization policy for this specific bean.
-
Configuration via Java Code (with
@Bean):When using Java-based configuration with
@Configurationand@Bean, beans are created at context startup by default. However, if you have enabled global lazy loading, you can override it for a specific bean:// Configuration class @Configuration public class AppConfig { @Bean @Lazy(false) // Indicates that this bean is not lazy public EagerSingletonBean eagerSingletonBean() { return new EagerSingletonBean(); } }Using
@Lazy(false)on a@Beanmethod is similar to using it at the class level with@Component. -
Global disable of Lazy Loading:
You can disable lazy loading globally for the entire application. This is not the most recommended approach, as it may increase startup time, but it exists:
-
Via
application.propertiesorapplication.yml:spring.main.lazy-initialization=false -
Via Java Code:
You can configure
SpringApplicationBuilder:// In the main application class public static void main(String[] args) { new SpringApplicationBuilder(YourApplication.class) .lazyInitialization(false) .run(args); }
-
By default, Spring Boot applications with Spring Data JPA will create repository beans at startup. Dependencies between beans also influence their creation order; a bean that others depend on is usually created earlier.
The choice of method depends on the context and preferences: @Lazy(false) at the bean level is the most granular and explicit, while global disabling affects all beans.