1

Is it possible to replace the below code creating applicationcontext and registering a shutdownhook:

ClassPathXmlApplicationContext context 
   = new ClassPathXmlApplicationContext(configLocation);
context.start();
context.registerShutdownHook();

with try-with-resources contruct, something like:

try (ClassPathXmlApplicationContext context 
       = new ClassPathXmlApplicationContext(configLocation)) {
        context.start();
    } catch (Exception e) {
        e.printStackTrace();
    }

I want to be able to catch any exceptions raised while loading app-context, so wondering if using try-with-resources will be fine and sufficient (ApplicationContext is AutoCloseable). Are both the above mentioned code snippets equivalent?

Shubhi224
  • 104
  • 6
  • See https://stackoverflow.com/questions/14184059/spring-applicationcontext-resource-leak-context-is-never-closed – Ori Marko Aug 29 '18 at 12:00
  • @user7294900 I know using try-with-resources if allowed. Need to know if it's sufficient and can be a replacement of shutdownhook registering mechanism? – Shubhi224 Aug 29 '18 at 12:22
  • No. The shutdown hook makes sure (kind of) that your applications resources get cleaned up nicely in a well defined maner. The try with resources might do that but (afaik) there isn't a guarantee. – M. Deinum Aug 29 '18 at 17:26
  • @M.Deinum So does it mean I should use both try-with-resources and a shutdownhook, as I have to catch an exception so I want to go with try-with-resources instead of simple try-catch ? What's the best approach? – Shubhi224 Aug 30 '18 at 04:36
  • You don't need to register the shutdown hook the context automatically does that for you, nor do you need to call `start` as that is automatically done in the constructor. You only need the `new ClassPathXmlApplicationContext`. Next to that what do you want to do with the catcher exception? And why are you even creating your own context (generally that is a bad thing to do). – M. Deinum Aug 30 '18 at 06:06
  • @M.Denium The shutdownhook is automatically registered only for a web app. As per the Spring doc:If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop environment; you register a shutdown hook with the JVM. I know start() method is redundant but I am least bothered of it. My concern is to be able to log error message for any failure during application context loading/app startup as org.springframework is set to warn and I don't want to change it. Just want to be able to log error message when application startup fails – Shubhi224 Aug 30 '18 at 06:24
  • @M.Denium WIth that concern in my mind, I was wondering if I could replace that shutdownHook() logic with a try-with-resources – Shubhi224 Aug 30 '18 at 06:28

0 Answers0