When my spring web app shuts down, is there an event I can wireup to somehow that I can perform some cleanup code to empty out some pools etc.
5 Answers
You Could use the following
destroy-method
as @amir75 recommends@PreDestroy annotation
Implement DisposableBean and override destroy method.
All the deatails about these can be found at Disposable Callbacks.

- 7,434
- 6
- 42
- 59

- 9,507
- 4
- 36
- 45
Based on the JSR-250 specification the best practice to use in modern spring application is the @PreDestroy
annotation since using this approach will decouple your beans from Spring.

- 8,904
- 6
- 49
- 75

- 71
- 1
- 2
Spring beans have a 'destroy-method' attribute, which will be invoked when you 'close' your context.
<bean id="bean1"
destroy-method="stop"
class="com.example.Bean" />
In order to close it, you'd call the close() method:
(or just shut down the container if appropriate)
Hope that helps..

- 8,860
- 3
- 29
- 39
The non-Spring way to handle this is to write a class that implements ServletContextListener
and do your cleanup in its contextDestroyed
method. You'd add your class as a context listener in web.xml.

- 19,704
- 14
- 78
- 96
-
1The trouble with this approach is that Spring is probably doing the same thing, and it is not obvious whether your custom servlet context listener will run before ... or after the Spring one. This could make life awkward. – Stephen C Dec 21 '11 at 05:56
-
I don't know why I answered a Spring questions with "the non-Spring way" but that was 9 years ago when I was new to Spring. Now that I have 9 more years of experience with Spring I say the accepted answer is correct, `@PreDestroy` is the right way. – Paul Dec 12 '20 at 12:30
According to the Spring Boot logback example project, you should close the context to clean up the logging system: https://github.com/spring-projects/spring-boot/commit/10402a651f1ee51704b58985c7ef33619df2c110
Example:
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleLogbackApplication.class, args).close();
}

- 479
- 5
- 6