26

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.

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

5 Answers5

37

You Could use the following

  1. destroy-method as @amir75 recommends

  2. @PreDestroy annotation

  3. Implement DisposableBean and override destroy method.

All the deatails about these can be found at Disposable Callbacks.

Anthony Raymond
  • 7,434
  • 6
  • 42
  • 59
Aravind A
  • 9,507
  • 4
  • 36
  • 45
7

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.

alex
  • 8,904
  • 6
  • 49
  • 75
7

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:

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/support/AbstractApplicationContext.html#close%28%29

(or just shut down the container if appropriate)

Hope that helps..

laher
  • 8,860
  • 3
  • 29
  • 39
5

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.

Paul
  • 19,704
  • 14
  • 78
  • 96
  • 1
    The 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
2

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();
    }
E3G
  • 479
  • 5
  • 6