Search code examples
javadependency-injectionsingletonguice

Accessing a Guice singleton from Injector


I'm using Guice to create a singleton in a Java application. I used the following method in my module class:

@Provides
@Singleton
public LinkedBlockingQueue<String> provideLinkedBlockingQueue() {
    return new LinkedBlockingQueue<>();
  }

In another class I attempted to grab an instance this way:

public class Resource {
  private final LinkedBlockingQueue<String> bufferQueue;

  @Inject
  public Resource(LinkedBlockingQueue<String> bufferQueue) {
    this.bufferQueue = bufferQueue;
  }

Finally, I want to access the same instance in my application from my injector and I tried to do that this way:

LinkedBlockingQueue<String> bufferQueue =
        injector.getProvider(LinkedBlockingQueue.class).get();

Is this the correct way to go about sharing an instance between the Resource class and in my application from my injector?


Solution

  • Is this the correct way to go about sharing an instance between the Resource class and in my application from my injector?

    No, it is not.

    You should use Key<LinkedBlockingQueue<String>> or TypeLiteral<LinkedBlockingQueue<String>> instead of LinkedBlockingQueue.class.

    For instance:

    injector.getProvider(new Key<LinkedBlockingQueue<String>>(){}).get();