Shutdown Equivalent of ApplicationContextInitializer
Asked Answered
K

3

5

How can I cleanly shut down resources used in an ApplicationContextInitializer implementation?

I've created an ApplicationContextInitializer implementation that uses the Curator project to connect to Zookeeper and acquire a properties file. It then creates a Properties instance , a PropertiesPropertySource and adds that to the context.

When the application shuts down, I'd like to be able to call close() on the CuratorFramework instance that was a member of my initializer. How is this best done?

Could I also pass the CuratorFramework instance into the context, so I can use it as a bean?

Kelsy answered 10/9, 2012 at 11:58 Comment(0)
I
6

In your ApplicationContextInitializer, you can add an ApplicationListener<ContextClosedEvent>:

class MyContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
        @Override
        public void initialize(ConfigurableApplicationContext applicationContext) {

            applicationContext.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {
                @Override
                public void onApplicationEvent(ContextClosedEvent event) {
                    /* Cleanup code */
                }
            });
        }
    }

Imprecision answered 25/7, 2019 at 10:58 Comment(0)
C
1

I would create a bean that gets the spring events, and use that to close curator,

public class CuratorDisposer implements DisposableBean { 
    private CuratorFramework delegate; //set through spring somehow

    public void destroy() {
          delegate.close();
    }  
}
Conjunctiva answered 10/9, 2012 at 13:42 Comment(0)
D
1

When the application shuts down, I'd like to be able to call close() on the CuratorFramework instance that was a member of my initializer. How is this best done?

You could have your initializer class implement ApplicationListener, and then register itself as a listener on the context. You would then receive the ContextClosedEvent when the context shuts down.

Could I also pass the CuratorFramework instance into the context, so I can use it as a bean?

You could possibly do something like this in your initializer (not tested):

RootBeanDefinition cfDef = new RootBeanDefinition(MethodInvokingFactoryBean.class);
cfDef.getPropertyValues().add("targetClass", MyInitializer.class);
cfDef.getPropertyValues().add("targetObject", this);
cfDef.getPropertyValues().add("targetMethod", "getCuratorFramework");
((BeanDefinitionRegistry)ctx).registerBeanDefinition("curatorFramework", cfDef);

and add a getCuratorFramework() method to your initializer class, returning the CuratorFramework you created at init time.

Dichogamy answered 10/9, 2012 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.