Shutting down Spring backed JavaFX application

This is just another short tip on how to combine JavaFX and the Spring Framework. These two technologies do not work perfectly together, but they can be made to cooperate. One of the two is the lead, meaning one is initialized first from the main method and therefore controls the lifecycle of the application. In my case this is the Spring framework as the user interface is optional. However I still want to handle the case where the user interface is closed (or the menu point quit is selected) and this should also shut down the application context of Spring.

There are three steps that should be taken:

  • Register the shutdown hooks for your application context. This has nothing to do with canceling the application in a controlled manner. This case covers things like Ctrl+C or kill -9.
((AbstractApplicationContext)context).registerShutdownHook();
  • Override the stop method of Application. When closing the application window, the stop method is called. You will want to hook into this method to signal the spring context that his end has come.
    @Override
    public void stop() throws Exception {
        System.out.println("Stopping the UI Application");

        stopUIApplicationContext();
        super.stop();
    }

In my case I used Guava’s EventBus to signal the context.

  • Finally in your code handling the context end it.
((AbstractApplicationContext)context).close();

That’s it, folks!