By default Spring container instantiates all configured beans at startup (eager loading). In some situations, however, beans might rarely be used during application life cycle. Loading them at startup will not be a good idea if they are going to use considerable resources/memory to get initialized. In those situations we may decide to initialize such beans only when they are first accessed by application code (i.e. initialize on demand). We can achieve that by using @Lazy annotation on bean configuration method.
Example
An example bean which is used rarely
package com.logicbig.example.bean;
import jakarta.annotation.PostConstruct;
public class RarelyUsedBean {
@PostConstruct
private void initialize() {
System.out.println("RarelyUsedBean initializing");
}
public void doSomething() {
System.out.println("RarelyUsedBean method being called");
}
}
An example bean which is used frequently
package com.logicbig.example.bean;
import jakarta.annotation.PostConstruct;
public class AlwaysBeingUsedBean {
@PostConstruct
public void init() {
System.out.println("AlwaysBeingUsedBean initializing");
}
}
Using @Lazy annotation and running main class
package com.logicbig.example;
import com.logicbig.example.bean.AlwaysBeingUsedBean;
import com.logicbig.example.bean.RarelyUsedBean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
@Configuration
public class AppConfig {
@Bean
public AlwaysBeingUsedBean alwaysBeingUsedBean() {
return new AlwaysBeingUsedBean();
}
@Bean
@Lazy
public RarelyUsedBean rarelyUsedBean() {
return new RarelyUsedBean();
}
public static void main(String... strings) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
System.out.println("Spring container started and is ready");
RarelyUsedBean bean = context.getBean(RarelyUsedBean.class);
bean.doSomething();
}
}
Output
AlwaysBeingUsedBean initializing Spring container started and is ready RarelyUsedBean initializing RarelyUsedBean method being called
Example Project
Dependencies and Technologies Used:
spring-context 6.1.2 (Spring Context) Version Compatibility: 3.2.3.RELEASE - 6.1.2Version List
×
Version compatibilities of spring-context with this example: