[Changing subject line to clarify that this is an HK2 issue, and to see
if I can get some help with it...]
On 4/21/2015 4:57 PM, Ric Bernat wrote:
>
> I have a number of classes that I have implemented as Features
> (javax.ws.rs.core.Feature), in order to have a singleton instance of
> them availabe within my application.
>
> For example:
>
> public class AgentSessionCacheFeature implements Feature {
> @Override
> public boolean configure(final FeatureContext context) {
> context.register(new AgentSessionCacheBinder());
> return true;
> }
> }
>
> The corresponding Binder instantiates the class:
>
> public class AgentSessionCacheBinder extends AbstractBinder {
> @Override
> protected void configure() {
> bind(new AgentSessionCache()).to(AgentSessionCache.class);
> }
> }
>
> I register the Feature in my Application as follows:
>
> @ApplicationPath("/*")
> public class MyApplication extends ResourceConfig {
> public MyApplication() {
> register(AgentSessionCacheFeature.class);
>
> This all works fine: the singleton instance is created, and I use it
> throughout my application.
>
> My question is: how can I get a hook to tell this instance when Tomcat
> is shutting down, so that it can release resources?
>
> I have created a class that implements ServletContextListener, and in
> that class I override the contextDestroyed method.
>
> @WebListener
> public class MyAppServletContextListener implements
> ServletContextListener {
>
> private final Logger logger =
> LoggerFactory.getLogger(MyAppServletContextListener.class);
>
> @Inject
> private AgentSessionCache agentSessionCache;
>
> @Override
> public void contextDestroyed(ServletContextEvent sce) {
> if (agentSessionCache != null) {
> agentSessionCache.shutdown();
> } else {
> logger.warn("MyAppServletContextListener.contextDestroyed:
> agentSessionCache == null.");
> }
> }
> }
>
> However, when contextDestroyed is called, my singleton instance is
> null. So perhaps it has already been destroyed separately by HK2
> before contextDestroyed is called? Or perhaps HK2 is not able to
> inject it into my ServletContextListener?
>
> In any case, my goal is to find a hook I can use to release resources
> from singleton classes I instantiate via the Feature/Binder strategy.
>
>