Closing Spring ApplicationContext

When creating a new Spring application, for example, through

final ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfiguration.class); 

Eclipse (STS 3.2.0) marks this as a potential resource leak, complaining that it never closes ("resource leak:" ac "never closes).

So far so good. Then I tried to study this question and could not find close() or shutdown() or a similar method that would even allow me to close ApplicationContext . Is this an Eclipse warning about leaving, a design intended, or am I missing something?

+4
source share
4 answers

You declare ac as ApplicationContext , which does not define the close() method. Instead, use any supertype AnnotationConfigApplicationContext that extends Closeable (e.g. ConfigurableApplicationContext ) by providing the close() method, you need to free all resources.

+5
source

If you are using Java 7, you can use the try-with-resources statement to do your job

 try (AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(...)) { ... } 
+5
source

Yes, the ApplicationContext interface does not have a close() method, but the child classes of AbstractApplicationContext and GenericApplicationContext have close() and destroy() . Therefore, I suggest using them instead. There is also a useful registerShutdownHook() method.

+4
source

Drag your ApplicationContext into ConfigurableApplicationContext, which defines the close () method:

((ConfigurableApplicationContext) appCtx) .close ();

see fooobar.com/questions/77427 / ...

0
source

Source: https://habr.com/ru/post/1487832/


All Articles