1

I'm using Jersey-2.19.x in my application to call rest APIs. Since jersey clients are expensive to create, I wanted to reuse the client for my API calls and therefore inject the client via guice injection.

Here is my guice code for injecting jersey client:

@Provides
@Singleton
Client getClient() {
  return ClientBuilder.newClient();
}

And here is my class that uses this injection:

@Inject
public MyClass(Client client) {
  this.client = client;
}

public callPost(String uri) {
  // code to set web target and invoke
}

Now my question is, how can I close this injected client? What happens if jersey clients are never closed? And what are some best practices for using jersey client via dependency injection?

Wonjoo Lee
  • 99
  • 3
  • 8
  • According to Guice documentation you should avoid injecting closable resources. Here you can find the detailed explanation and the possible workarounds. https://github.com/google/guice/wiki/Avoid-Injecting-Closable-Resources – olgacosta Sep 04 '19 at 14:08

1 Answers1

0

You need a shutdown hook.

Here is a good article that might be somewhat of an overkill for your situation: https://richardstartin.github.io/posts/lifecycle-management-with-guice-provision-listeners

If you want to keep things simpler, and you don't need to close anything but the Jersey client, you could try something like this:

public static void main(String args[]) {
  Injector injector = Guice.createInjector(/* modules... */);
  Client jerseyClient = injector.getInstance(Client.class);
  Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override public void run() { 
      jerseyClient.close(); 
    }
  });
  // proceed as normal
}
iluxa
  • 6,941
  • 18
  • 36