Does spring have a shutdown process to put cleanup code?
Asked Answered
E

5

27

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.

Engulf answered 21/12, 2011 at 5:14 Comment(0)
L
38

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.

Laterite answered 21/12, 2011 at 5:50 Comment(0)
S
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..

Shrive answered 21/12, 2011 at 5:36 Comment(0)
O
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.

Oriente answered 27/1, 2016 at 21:41 Comment(0)
E
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.

Eyelash answered 21/12, 2011 at 5:41 Comment(2)
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.Kilroy
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.Eyelash
G
1

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();
    }
Gourmont answered 6/9, 2016 at 3:8 Comment(2)
Dose this close all connections opened to datasource?Sirajuddaula
I don't think that's what this example says. This example shows a minimal Spring application that is started, logs a couple of messages (from a method annotated with @PostConstruct) and is then immediately closed. The question is about reacting to the application context closing and doing some cleanup (and @PreDestroy is probably the best way to do that, as suggested in other answers)Secretory

© 2022 - 2024 — McMap. All rights reserved.