On Monday, November 25, 2013 9:57:14 PM UTC-5, Benson Margulies wrote:
>
> At the moment, I'd like to use guice to do one very constrained bit of DI.
>
> Given a Map<String, Object>, and an Object with some annotations that 
> indicate injection targets, inject the values from the map into the target 
> object, performing simple type conversions (string->int, string->File, etc).
>
> Where would I look, if anywhere, in the Guice API to do this?
>

I concur with Cedric - if you need the map, just inject the map.

If the map is something that's accessible at startup and the types in it 
are simple and known (i.e. you don't want to actually bind a superclass or 
interface of the values in the map), you could do something like

for (Map.Entry<String,Object> e : theMap.entrySet()) {
  
 
bind(e.getValue().getClass()).annotatedWith(Names.named(e.getKey()).toInstance(e.getValue());
}

(to do that without compiler warnings a bit of generics hackery is needed - 
something like 
private <T> bind(Class<T> type, Object o, String key) { 
bind(type).annotatedWith(Names.named(key)).toInstance(type.cast(o)); }
)...and then reference them, e.g.

@Inject
public Foo (@Named("someKey") Integer someValue) {...}

There are plenty of solutions for generically binding data from properties 
files or other sorts of application configuration stuff to @Named.  I am 
the author of one:
https://github.com/timboudreau/giulius
If the map you need access to is some sort of load-on-startup application 
configuration, it's probably best not to reinvent the wheel, and nobody's 
code improved by being cluttered with code to load a config file from 
somewhere.  So if it will let you delete some code, a library that handles 
loading settings in some standard way is probably a good idea.

The thing to remember is that you *must* know all the key names you want to 
bind at injector creation time if you want to use @Named.

-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.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to