Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring Boot context initializer: make pre-refresh customization narrow

Last updated: 5 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

An ApplicationContextInitializer runs before bean definitions load; it is suitable for early context setup, not normal service construction.

Use the early hook deliberately

A host application embeds the receipt module and needs to attach one context identifier before configuration classes are parsed. A SpringApplication initializer receives the ConfigurableApplicationContext before refresh and can set that early value. Ordinary services should still be declared as components or beans, so their dependencies, conditions and lifecycle remain visible to the container. ApplicationContext ownership] provides the baseline.

Know what is unavailable

The initializer does not have a fully refreshed context. Do not call getBean for a service that has not been constructed, start a scheduler or open a database connection from the hook. Register the initializer programmatically before run for one application, or through an explicit library registration when every consuming app needs it. BeanFactoryPostProcessor] is a later mechanism for editing definitions; BeanPostProcessor] operates on bean instances.

Prove ordering and absence

Start the same application with and without the initializer. Assert the context identifier is visible during configuration loading, while normal beans are created once and shut down normally. A test that registers the initializer after run cannot prove anything: the context has already passed that phase. Keep the early value non-secret if it may enter logs or diagnostic names.

Implementation contract

Java
// In main(String[] args):
String deploymentSlot = System.getenv().getOrDefault("DEPLOYMENT_SLOT", "local");
SpringApplication receiptApplication = new SpringApplication(ReceiptApplication.class);
receiptApplication.addInitializers(context ->
    context.setId("receipt-service-" + deploymentSlot));
ConfigurableApplicationContext runningContext = receiptApplication.run(args);

Cost and verification

The hook runs once per context start. Long or blocking work here delays readiness and makes startup failures harder to attribute.

Common Mistakes

  • Do not request application service beans before context refresh.
  • Do not register the initializer after the application has run.
  • Do not use an initializer for ordinary constructor-injected services.

Read next

Spring ApplicationContext: construct and close an object graph, Spring BeanFactoryPostProcessor: inspect definitions before instances exist, Spring BeanPostProcessor: instance callbacks and the early-bean trap, Spring Boot configuration validation: reject an unusable relay before work starts, Spring Boot FailureAnalyzer: turn one startup exception into an actionable failure.

spring
spring-boot
boot-context-initializer-boundary
Storage details