When we create an ApplicationContext in Spring, such as:
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
Spring performs the following steps behind the scenes to create and manage beans:
1. Register Bean Definitions
Spring parses configuration classes (annotated with @Configuration, @Component, @Bean, etc.) and generates BeanDefinition objects for each bean. These definitions describe how each bean should be created, including its class type, scope, dependencies, etc.
- It uses processors like ConfigurationClassPostProcessorto scan and parse these annotations.
- All BeanDefinitions are stored in an internal registry within theBeanFactory.
2. Refresh Context
The refresh() method in ApplicationContext is a complex lifecycle method. Key steps include:
- 
invokeBeanFactoryPostProcessors()— modifies or adds additionalBeanDefinitions.
- 
registerBeanPostProcessors()— sets up hooks to customize bean creation (e.g. AOP).
- 
finishBeanFactoryInitialization()— triggers the creation of singleton beans.
3. Instantiate Beans
When getBean() is called or during pre-instantiation of singletons, Spring follows:
- Create instance — using constructor or factory method.
- 
Inject dependencies — by field, setter, or constructor (@Autowired,@Value).
- 
Apply initialization callbacks — like @PostConstruct, or interfaces likeInitializingBean.
- Apply BeanPostProcessors — allows enhancement or proxying (used by AOP, @Transactional).
4. Store in Singleton Cache
If the bean scope is singleton (default), Spring caches the instance for future use.
Summary Flowchart:
@Configuration + @ComponentScan
        ↓
parse to BeanDefinition
        ↓
register in BeanFactory
        ↓
on refresh(): createBean()
        ↓
- instantiate
- inject dependencies
- initialize
- apply post processors
        ↓
put into singleton cache
 

 
    
Top comments (0)