简体   繁体   中英

Binding A HashMap Instance In Guice

I have a method that returns a Map():

private Map<String, Catalog> readCatalogFromXml(String xmlFile) {
    // blah blah read XML via DOM
}

However, I need to bind the results of that call to a single instance to be injected into multiple classes. I've been looking over the docs for MapBinder but am confused. I'm probably missing something simple, can anyone assist?

Jason

Just implement a provider in your Module class:

public class ModuleImpl extends AbstractModule {
    @Override
    protected void configure() {
        // bind whatever needed
    }

    @Singleton
    @Provides
    Map<String, Catalog> provideMap(@XMLFile String xmlFile) {
        // create an instance of your class
        return myClass.readCatalogFromXml(xmlFile);
    }
}

If you just need the returned Map injected, I would ...

  1. define a subclass "@Singleton public class MyInjectedMap extends HashMap { }"
  2. bind a Provider < MyInjectedMap > to produce instances

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