DEV Community

Liu yu
Liu yu

Posted on

How Does ApplicationContext Create Beans in Spring?

When we create an ApplicationContext in Spring, such as:

ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
Enter fullscreen mode Exit fullscreen mode

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 ConfigurationClassPostProcessor to scan and parse these annotations.
  • All BeanDefinitions are stored in an internal registry within the BeanFactory.

2. Refresh Context

The refresh() method in ApplicationContext is a complex lifecycle method. Key steps include:

  • invokeBeanFactoryPostProcessors() — modifies or adds additional BeanDefinitions.
  • 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:

  1. Create instance — using constructor or factory method.
  2. Inject dependencies — by field, setter, or constructor (@Autowired, @Value).
  3. Apply initialization callbacks — like @PostConstruct, or interfaces like InitializingBean.
  4. 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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)