Skip to content

ApplicationContext lifecycle management

ApplicationContext lifecycle management refers to the creation, maintenance, and termination of Spring application contexts, particularly when dealing with hierarchical parent-child relationships. Managing the lifecycle involves registering configurations, establishing parent hierarchies, explicitly refreshing contexts to initialize beans, and closing contexts to release resources.

Context Hierarchy and Visibility

In a hierarchical structure, a child context is coupled with a parent context using the setParent(ApplicationContext parent) method.^[600-developer__java__spring__multipleApplicationContext.md]

A key characteristic of this hierarchy is unidirectional visibility: child contexts can access and retrieve beans defined in the root (parent) context, but the parent context cannot access beans defined within its children.^[600-developer__java__spring__multipleApplicationContext.md]

Lifecycle Phases

The management of an ApplicationContext generally follows these stages:

  1. Instantiation: A new context object is created, typically via new AnnotationConfigApplicationContext().
  2. Configuration: Beans are registered using methods like registerBean(), and a display name may be set using setDisplayName().
  3. Hierarchy Construction: Relationships are established by calling setParent().^[600-developer__java__spring__multipleApplicationContext.md]
  4. Refresh: The refresh() method must be called explicitly to process the configuration and instantiate the beans.^[600-developer__java__spring__multipleApplicationContext.md]
  5. Active Use: The application retrieves beans using getBean().
  6. Shutdown: The close() method is called to destroy the context and release resources.

Environment Merging

When a parent context is set, the environment configuration is inherited by the child. Specifically, if the parent context possesses a ConfigurableEnvironment, the child context will merge its parent's environment into its own during the setParent process.^[600-developer__java__spring__multipleApplicationContext.md]

Status Tracking

The status of a context can be monitored using the isActive() method.^[600-developer__java__spring__multipleApplicationContext.md] A context returns true for isActive() only after it has been successfully refreshed. Once close() is invoked, isActive() returns false, and attempting to retrieve beans from a closed context will typically result in errors.^[600-developer__java__spring__multipleApplicationContext.md]

  • [[Inversion of Control]]
  • [[Dependency Injection]]

Sources