The last bit of code there can't work - Guice can't see inside function
bodies and fiddle with things before they're called.
I think
bind(Mongo.class).annotatedWith(Names.named("someName")).to...(...)
is what you're looking for. You didn't include the code that sets up your
bindings, so I don't know what you *did* do, but probably that's what
you're missing. Consider injecting @Named(...) DBCollection or @Named(...)
DB instead, and hide the string mapping inside a Provider - the code that's
going to be called probably isn't interested in making a database
connection so much as using one. So just find a way to provide the
objects, already configured, that your code needs and that way the
configuration and setup code is completely separated from the business
logic.
BTW, for general loading of properties files and binding them to @Named,
have a look at giulius - https://github.com/timboudreau/giulius
It sounds like the general pattern of what you're doing would look
something like (copied from some code I had lying around):
final class MongoModule extends AbstractModule {
private final Map<String,String> nameForCollection = new HashMap<>();
public MongoModule addNamedCollectionBinding(String collectionName,
String bindingName) {
nameForCollection.put(bindingName, collectionName);
return this;
}
@Override
protected void configure() {
try {
MongoClient mc = new MongoClient(...);
bind(MongoClient.class).toInstance(mc);
DB db = mc.getDB("timetracker"); // probably you want to look
this up more lazily
bind(DB.class).toInstance(db);
for (Map.Entry<String,String> e : nameForCollection.entrySet())
{
bind(DBCollection.class).annotatedWith(Names.named(e.getValue())).toProvider(new
CollectionProvider(e.getKey(), binder().getProvider(DB.class)));
}
} catch (UnknownHostException ex) {
Exceptions.chuck(ex);
}
bind(Realm.class).toProvider(RealmProvider.class);
}
static class CollectionProvider implements Provider<DBCollection> {
private final String name;
private final Provider<DB> db;
public CollectionProvider(String name, Provider<DB> db) {
this.name = name;
this.db = db;
}
@Override
public DBCollection get() {
return db.get().getCollection(name);
}
}
It's a pattern that's pretty reusable for whatever flavor of object you
want injected using @Named, and keeps the client code nicely
boilerplate-free.
-Tim
--
You received this message because you are subscribed to the Google Groups
"google-guice" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/google-guice?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.