Quick revision
The short answer
refresh() first prepares the environment and obtains a bean factory loaded with bean definitions. It then runs the BeanFactoryPostProcessors, including ConfigurationClassPostProcessor, which parses @Configuration classes and scans for components, and registers the BeanPostProcessors. Next it sets up the MessageSource and the event multicaster and calls onRefresh, where Spring Boot creates its embedded web server. Finally it creates all non-lazy singletons and finishes the refresh by starting Lifecycle beans and publishing ContextRefreshedEvent.
What to remember
In this answer, we followed ApplicationContext.refresh() in order. It prepares the environment and obtains a bean factory with its definitions, invokes the BeanFactoryPostProcessors, including ConfigurationClassPostProcessor which parses @Configuration classes and scans components, and registers the BeanPostProcessors. It then initialises the MessageSource and the event multicaster and calls onRefresh, where Spring Boot creates the embedded web server. Finally it instantiates all non-lazy singletons and finishes the refresh by starting Lifecycle beans, which is when Boot's server begins listening, and publishing ContextRefreshedEvent.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
refresh() first prepares the environment and obtains a bean factory loaded with bean definitions. It then runs the BeanFactoryPostProcessors, including ConfigurationClassPostProcessor, which parses @Configuration classes and scans for components, and registers the BeanPostProcessors. Next it sets up the MessageSource and the event multicaster and calls onRefresh, where Spring Boot creates its embedded web server. Finally it creates all non-lazy singletons and finishes the refresh by starting Lifecycle beans and publishing ContextRefreshedEvent.
Why this question is asked
Every Spring application, from a ten-line test to a large Spring Boot service, goes through AbstractApplicationContext.refresh() exactly once at startup. Knowing its steps in order answers many practical questions: why a BeanFactoryPostProcessor cannot use @Autowired, why a bean that makes a network call in its constructor slows startup, and when the web server actually accepts traffic. Interviewers ask this to separate people who use Spring from people who can debug it. In this answer, we will follow refresh() phase by phase, see what each phase is for and what can go wrong in it, and place Spring Boot's embedded server in the sequence.
1A Quick Recap: What Refresh Means
An ApplicationContext is Spring's container: it holds bean definitions, the recipes for creating beans, and the beans created from them. Creating the context object does very little. The real work happens in refresh(), a template method in AbstractApplicationContext that every context type inherits. Subclasses, such as Spring Boot's ServletWebServerApplicationContext, fill in some steps but keep the order.
It helps to keep two ideas apart. Before a certain point, Spring only works with definitions: it reads and changes recipes. After that point, it creates real objects. Most of the rules about what you can and cannot do in each extension point come from which side of that line it runs on.
2Phase 1: Preparing and Loading Definitions
refresh() starts with prepareRefresh(), which records the start time, marks the context active and initialises and validates property sources, so required properties are checked early. Then obtainFreshBeanFactory() gets the internal DefaultListableBeanFactory. For XML-based contexts, this is where the XML files are read into definitions; for annotation-based contexts the factory already holds the registered configuration classes.
prepareBeanFactory() then configures the factory with standard parts: the class loader, the expression resolver for #{...} SpEL expressions, the ability to inject the context itself, the Environment and its properties as beans, and a few built-in post-processors. postProcessBeanFactory() is a hook for subclasses; web contexts use it to register request and session scopes.
3Phase 2: BeanFactoryPostProcessors Change the Recipes
invokeBeanFactoryPostProcessors() runs every BeanFactoryPostProcessor, an extension that can read and change bean definitions before any normal bean exists. The most important one is ConfigurationClassPostProcessor. It parses @Configuration classes, follows @ComponentScan to find @Component classes, processes @Import, @Bean methods and @PropertySource, and in Spring Boot handles the auto-configuration imports. So for an annotation-based application, this is the moment when most bean definitions come into existence.
Other processors run here too, for example PropertySourcesPlaceholderConfigurer, which replaces ${...} placeholders in definitions. Processors that implement BeanDefinitionRegistryPostProcessor run first and can add new definitions; then ordinary processors run, ordered by PriorityOrdered, Ordered and the rest. Because no normal beans exist yet, a BeanFactoryPostProcessor must not depend on @Autowired fields of ordinary beans, which is also why @Bean methods returning one should be static.
4Phase 3: Registering BeanPostProcessors
registerBeanPostProcessors() creates every BeanPostProcessor and registers it with the factory, again in priority order. A BeanPostProcessor runs around the creation of every later bean. AutowiredAnnotationBeanPostProcessor fills @Autowired and @Value, CommonAnnotationBeanPostProcessor handles @PostConstruct, @PreDestroy and @Resource, and the auto-proxy creators wrap beans in proxies for @Transactional, @Async and AOP aspects.
Notice the order: they must be registered before the normal beans are created, or those beans would miss their injection and proxies. If a BeanPostProcessor itself depends on ordinary beans, those beans get created early, before all processors are ready. Spring then logs an INFO message saying a bean is not eligible for getting processed by all BeanPostProcessors, which usually means it will not be proxied.
5Phase 4: Messages, Events and onRefresh
initMessageSource() sets up the MessageSource for localised messages, using a bean named messageSource if one is defined. initApplicationEventMulticaster() sets up the component that delivers events to listeners. Then onRefresh() is a hook for subclasses. Spring Boot's web contexts use it to create the embedded web server, Tomcat, Jetty or Undertow, so that servlets and filters can be registered with it.
A detail worth knowing: creating the server is not the same as accepting traffic. Spring Boot creates the server in onRefresh, but it starts the connectors, the moment the port actually accepts requests, through a lifecycle bean at the end of refresh, after all singletons exist. That is why a service with slow beans shows nothing listening on its port until the very end. registerListeners() then attaches the ApplicationListener beans and publishes any early events that were waiting.
6Phase 5: Creating Singletons and Finishing
finishBeanFactoryInitialization() creates every non-lazy singleton. For each one, Spring instantiates it, injects dependencies, runs the BeanPostProcessors before initialisation, calls the init methods such as @PostConstruct and afterPropertiesSet, and runs the BeanPostProcessors after initialisation, which is where proxies replace the raw object. In most applications this is the longest phase, because this is where our constructors and @PostConstruct methods run. After all singletons exist, beans that implement SmartInitializingSingleton get a callback.
Finally finishRefresh() initialises the LifecycleProcessor, starts every SmartLifecycle bean that is auto-startup, such as message listener containers, schedulers and Spring Boot's web server connectors, and publishes ContextRefreshedEvent. Spring Boot then publishes ApplicationStartedEvent and ApplicationReadyEvent from SpringApplication after refresh returns. If any step throws, refresh destroys the singletons created so far and rethrows, so startup fails cleanly.
- Prepare refreshstart time, validate required properties
- Obtain and prepare the bean factorydefinitions loaded, standard beans added
- Invoke BeanFactoryPostProcessorsparse
@Configuration, scan components - Register BeanPostProcessors
@Autowired,@PostConstruct, proxies - MessageSource and event multicaster
- onRefreshSpring Boot creates the web server
- Register listenersearly events delivered
- Create non-lazy singletonsour constructors and
@PostConstructrun here - Finish refreshstart Lifecycle beans, publish
ContextRefreshedEvent
9 steps in order. Play them, or step through them one at a time.
Steps 3 and 4 work on recipes; step 8 creates the real objects.
7Follow-up questions
Can refresh() be called twice?
Most contexts used in modern applications, such as GenericApplicationContext and AnnotationConfigApplicationContext, allow refresh only once and throw an IllegalStateException on a second call. Older refreshable contexts, such as the XML-based ones, can reload their definitions, but applications rarely rely on that.
Where should I put code that needs every bean to be ready?
Use an ApplicationReadyEvent listener in Spring Boot, or SmartInitializingSingleton, or a SmartLifecycle bean if it must also stop cleanly. Code in a @PostConstruct method runs while other singletons may not exist yet, so it should only touch its own dependencies.
Why does a slow @PostConstruct delay the web server?
Because all non-lazy singletons are created in finishBeanFactoryInitialization, and the server's connectors are only started afterwards in finishRefresh. A bean that calls a remote service for 20 seconds during initialisation therefore delays the moment the port starts listening by 20 seconds.
8Conclusion
In this answer, we followed ApplicationContext.refresh() in order. It prepares the environment and obtains a bean factory with its definitions, invokes the BeanFactoryPostProcessors, including ConfigurationClassPostProcessor which parses @Configuration classes and scans components, and registers the BeanPostProcessors. It then initialises the MessageSource and the event multicaster and calls onRefresh, where Spring Boot creates the embedded web server. Finally it instantiates all non-lazy singletons and finishes the refresh by starting Lifecycle beans, which is when Boot's server begins listening, and publishing ContextRefreshedEvent.
Open with
refresh is a template method in AbstractApplicationContext, and I think of it as two halves: first Spring works on bean definitions, then it creates real beans. It starts with prepareRefresh, which records the start and validates required properties, then obtainFreshBeanFactory and prepareBeanFactory, so we have a DefaultListableBeanFactory with the standard infrastructure registered.
Then, if they want more
Then comes invokeBeanFactoryPostProcessors. The key one is ConfigurationClassPostProcessor, which parses the @Configuration classes, does component scanning, handles @Import and @Bean methods and, in Boot, the auto-configuration imports, so this is where most definitions appear. Placeholder resolution also happens here.
Next, registerBeanPostProcessors creates the processors that handle @Autowired, @PostConstruct and the proxies for @Transactional; they must be ready before ordinary beans are created. Then initMessageSource, initApplicationEventMulticaster and onRefresh, which in Spring Boot creates the embedded Tomcat or Jetty. After registering listeners, finishBeanFactoryInitialization creates all non-lazy singletons, which is usually the slowest part because our constructors and init methods run there.
Finally finishRefresh starts the SmartLifecycle beans, including Boot's web server connectors, so that is when the port actually listens, and it publishes ContextRefreshedEvent. Boot then publishes ApplicationReadyEvent after refresh returns.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Core technologies
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "What happens during ApplicationContext.refresh()? Name the main steps in order.": https://scrivio-interview-library.netlify.app/spring-boot/ioc-container/ab2ce9d174/