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

Spring lifecycle cleanup: close container-owned resources

Last updated: 29 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A destruction callback releases resources owned by a bean when the container ends that bean’s managed lifecycle.

Download Spring source kit

This lesson uses the downloadable source kit: Java 21, Spring Boot 4.0.8 and its managed Spring Framework 7 dependencies. The version is pinned for repeatable builds.

The owner must be able to stop

ClosingChannel implements DisposableBean and records destruction. CoreBoundaryTest first observes an open channel, closes the context, and then observes the closed state. The test proves that callback delivery for this singleton; it does not demonstrate flushing a remote transport.

Objects that start threads should also define termination and interruption behavior. A callback that returns before its workers finish can leave writes in flight after the application claims to have stopped. Resource ownership includes the work using the resource.

Initialization can fail halfway

A resource-acquiring constructor or initialization callback can throw after opening something. The partially created object may never become a normal managed bean. Release any resource already acquired when that failure path occurs.

Java resource scopes remain useful inside a bean operation. Container lifetime is usually much longer than a file read or transaction, so do not keep short-lived descriptors open merely because the service is a singleton.

Checked source

Java
public static class ClosingChannel implements DisposableBean {
    public boolean closed;
    public void destroy() { closed = true; }
}

Test the boundary

Run mvn test in the source-kit directory. CoreBoundaryTest checks the behavior described here. Java excerpts belong to the named source-kit classes; they are not independent source files unless the complete class is shown.

Costs and boundaries

Closing should have a bounded wait or an explicit failure policy. This boolean fixture only verifies lifecycle delivery; graceful draining, failed flushes and forced process termination require their own tests.

Common Mistakes

  • Close contexts created by tests.
  • Do not assume prototype cleanup matches singleton cleanup.
  • Handle partial initialization failures.

Read next

Spring bean scopes: singleton identity is not thread safety, Actuator health, Java try-with-resources: close order and suppressed failures.

spring
spring-boot
lifecycle-cleanup
Storage details