skip to content

ApplicationContext Implementations & refresh()

The concrete context classes you can instantiate — annotation-based, XML, or generic — and what refresh() and close() do as they walk the startup phases. Interviewers ask this to see whether you can narrate container startup instead of treating it as magic.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

questions

5

What is an ApplicationContext, and what are the main concrete implementations you would instantiate?

level: juniorimportance: must knowfreq 70%

answer

  1. BeanFactory + enterprise features
  2. AnnotationConfig / ClassPathXml / Generic
  3. convenience ctors call refresh() for you
  4. Generic = you call refresh()
  5. close() runs destroy callbacks

basics

~10 s

ApplicationContext is Spring's IoC container that creates, wires, and manages beans. Common implementations: AnnotationConfigApplicationContext (Java/annotation config), ClassPathXmlApplicationContext (XML config), and GenericApplicationContext (flexible, programmatic registration).

solid answer

~30 s

ApplicationContext is Spring's central IoC container: it reads bean definitions, instantiates beans, injects dependencies, and adds enterprise features on top of a plain BeanFactory (event publishing, message source/i18n, resource loading, environment/property access). The three you construct directly are AnnotationConfigApplicationContext (scans/registers @Configuration and @Component classes), ClassPathXmlApplicationContext (loads bean definitions from XML on the classpath), and GenericApplicationContext (a general-purpose context where you register bean definitions or call registerBean yourself, then invoke refresh()). In practice most apps use AnnotationConfigApplicationContext; Spring Boot uses a subclass (AnnotationConfigServletWebServerApplicationContext / AnnotationConfigApplicationContext) under the hood.

code

java · 13 lines
java
// Annotation/Java config — refresh() runs inside this constructor
try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
    MyService svc = ctx.getBean(MyService.class);
    svc.run();
}

// XML config
var xmlCtx = new ClassPathXmlApplicationContext("beans.xml");

// Generic — YOU register then refresh exactly once
var generic = new GenericApplicationContext();
new AnnotatedBeanDefinitionReader(generic).register(AppConfig.class);
generic.refresh();

go deeper

for a junior

Name the three implementations and state ApplicationContext is the IoC container that builds and injects beans.

for a middle

Explain it extends BeanFactory with events/i18n/resources/environment, and note which constructors auto-call refresh().

for a senior

Contrast the class hierarchies (Generic vs Refreshable) and eager singleton instantiation, and mention Boot's web context subclass.

for a principal

Discuss when you'd pick GenericApplicationContext for programmatic bootstrap, lifecycle/close semantics, and how the context participates in the broader startup pipeline.

**IoC container.** Inversion of Control means the framework, not your code, is responsible for constructing objects and supplying (injecting) their dependencies. In Spring the container that does this is described by two interfaces: `BeanFactory` (the minimal container: get a bean by name/type, lazy instantiation) and `ApplicationContext`, which *extends* `BeanFactory` and layers on enterprise features: - **Event publishing** — `ApplicationEventPublisher` / `ApplicationListener`. - **Message source** — i18n via `MessageSource`. - **Resource loading** — `getResource(...)` returning `Resource` (classpath:, file:, URL). - **Environment abstraction** — `Environment`, property sources, active profiles. - **Automatic detection and application of `BeanFactoryPostProcessor` / `BeanPostProcessor`** (their *mechanics* are covered by a sibling topic; here just note the context wires them for you). **Concrete implementations you construct directly:** 1. `AnnotationConfigApplicationContext` — configured from Java: pass `@Configuration` classes and/or base packages to `scan(...)`. Detects `@Component`, `@Service`, `@Bean`, etc. It *extends* `GenericApplicationContext`. 2. `ClassPathXmlApplicationContext` — loads `<bean>` definitions from one or more XML files on the classpath. Sibling `FileSystemXmlApplicationContext` loads from the filesystem. These extend `AbstractRefreshableApplicationContext`. 3. `GenericApplicationContext` — a flexible base you use when you want to register bean definitions programmatically (via readers like `XmlBeanDefinitionReader`, `AnnotatedBeanDefinitionReader`, `ClassPathBeanDefinitionScanner`, or the functional `registerBean`) and then call `refresh()` yourself exactly once. **Key behavioral difference — who calls refresh():** The annotation and XML convenience contexts call `refresh()` for you inside their constructor (the constructor that takes config classes / xml locations). A bare `GenericApplicationContext` does *not*: you register beans and then call `refresh()` manually. **When to use which:** modern apps use annotation/Java config (`AnnotationConfigApplicationContext`, or Boot's auto-created web variant). XML contexts appear in legacy codebases. `GenericApplicationContext` is used for programmatic/functional bean registration, tests, and embedding Spring in a custom bootstrap. **Gotchas:** Always `close()` the context (or use try-with-resources — `ConfigurableApplicationContext` implements `AutoCloseable`) so `@PreDestroy`/destroy callbacks and `SmartLifecycle.stop()` run. Registering `registerShutdownHook()` ties context close to JVM shutdown.

  • Which of these implementations calls refresh() automatically and which does not?
    The convenience constructors of AnnotationConfigApplicationContext and ClassPathXmlApplicationContext (the ones taking config classes / xml locations) call refresh() themselves. A bare GenericApplicationContext (and AnnotationConfigApplicationContext's no-arg constructor) require you to call refresh() manually after registering beans.
  • How does ApplicationContext differ from BeanFactory?
    ApplicationContext extends BeanFactory and adds event publishing, i18n MessageSource, resource loading, the Environment/profile abstraction, and eager singleton pre-instantiation plus automatic post-processor detection. BeanFactory is the lower-level, lazy container rarely used directly.

saying these in an interview costs you the question

  • Saying ApplicationContext and BeanFactory are unrelated / competing containers
  • Claiming ClassPathXmlApplicationContext can only hold XML-declared beans and can't use annotations
  • Thinking every context lazily creates singletons (contexts eagerly pre-instantiate non-lazy singletons on refresh)
  • Forgetting to close the context so destroy callbacks never fire

context

open as a page

Walk through what happens when refresh() is called on an ApplicationContext.

level: seniorimportance: must knowfreq 60%

basics

~10 s

refresh() is the startup routine: it prepares and loads the bean factory, applies configuration post-processors, registers post-processors, sets up the message source, event multicaster, and listeners, eagerly creates all non-lazy singletons, then publishes ContextRefreshedEvent.

open as a page

What is an ApplicationContextInitializer and when does it run?

level: middleimportance: should knowfreq 30%

basics

~10 s

ApplicationContextInitializer is a callback you implement to configure the ConfigurableApplicationContext before refresh() is called. It's commonly used in Spring Boot to add property sources, activate profiles, or register beans very early in startup.

open as a page

How do you register beans programmatically with GenericApplicationContext and registerBean, and when would you do that?

level: seniorimportance: should knowfreq 35%

basics

~10 s

Create a GenericApplicationContext, call registerBean(...) passing a class (and optionally a supplier/lambda and customizers) for each bean, then call refresh() once. This is the functional bean-registration style — useful for lightweight, reflection-free wiring.

open as a page

Which contexts can be refreshed more than once, and what are the close()/shutdown semantics?

level: principalimportance: nice to knowfreq 18%

basics

~10 s

AbstractRefreshableApplicationContext subclasses (like ClassPathXmlApplicationContext) can call refresh() repeatedly to reload definitions; GenericApplicationContext (and AnnotationConfigApplicationContext) can only refresh once. close() stops lifecycle beans and runs destroy callbacks; registerShutdownHook ties that to JVM exit.

open as a page