简体   繁体   中英

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM