Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bean Lifecycle Management Spring Boot

I am currently trying to deploy a Spring Boot Application into an external Tomcat instance, and am running into some questions regarding how to best manage the instantiation of certain things.

As presently structured I have something along the lines of

public class MyClass extends SpringBootServletInitializer{


@Bean
public ThreadPool pool(){
    return new ThreadPool();
}

@Bean
public BackgroundThread setupInbox() {
    BackgroundThread inbox = new BackgroundThread(pool());
    inbox.start();
    return inbox;
}

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(MyClass.class);
}

public static void main(String[] args) throws Exception {
    SpringApplication.run(MyClass.class, args);
}


}

where BackgroundThread is a thread that is listening to an AMQP type messaging queue for new jobs. I know Spring offers some RabbitMQ ways to do this, but we are not using Rabbit for this so it doesn't help.

The entire purpose of this *.war file that is being deployed is to expose some functionality to the wire via messaging, so my question is what is the best way to instantiate, start and then destroy the BackgroundThread through the lifecycle of Spring? XML Configuration?

like image 342
schriste92 Avatar asked Sep 07 '16 12:09

schriste92


1 Answers

From the docs:

The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best practice for receiving lifecycle callbacks in a modern Spring application. Using these annotations means that your beans are not coupled to Spring specific interfaces.

For details see Section 7.9.8, “@PostConstruct and @PreDestroy”

Those annotation are meant to be put on some init and cleanup methods:

@PostConstruct
public void initAfterStartup() {
    ...
}

@PreDestroy
public void cleanupBeforeExit() {
    ...
}

Also useful :

Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface, or the @PreDestroy annotation) can be used.

In addition, beans may implement the org.springframework.boot.ExitCodeGenerator interface if they wish to return a specific exit code when the application ends.

like image 65
Fabien Benoit-Koch Avatar answered Oct 17 '22 02:10

Fabien Benoit-Koch