views:

446

answers:

3

I've used Spring before (and like it), but thought I'd take a look at Guice.

Is there a way to initialize something like maps or lists into beans using Guice?

For instance, I've done the following before in Spring to inject a list of items I want to process into some bean.

<property name="FilesToProcess">
   <list>
      <value>file1.xml</value>
      <value>file2.xml</value>
   </list>
</property>

How can I do this in Guice?

+4  A: 

Guice2 has MultiBindings and MapBindings, which should work for you.

http://code.google.com/p/google-guice/wiki/Changes20

Updated:

After looking at this again, it seems that you may be asking how you can inject runtime values into Guice, perhaps as arbitrary objects.

Guice is very focused around doing everything as typesafe code, so it doesn't lend itself naturally to this. What I've done to provide input to Guice is to create an XML schema and use jaxb to suck this in and inject the resulting objects.

There is a Names.bindProperties method for binding regular old properties into Guice constants.

There is also some level of integration with Spring, so you may want to look at this as well.

Dave Stenglein
Thanks! Your update exactly answered my question.
Vinnie
+1  A: 

Guice lets you inject type literals. The syntax is a little strange. There is a blog entry that explains why.

The binding would look something like this:

public class SampleModule extends AbstractModule {
    protected void configure() {
        bind(new TypeLiteral<List<String>>() {}).
                annotatedWith(Names.named("FilesToProcess")).
                toInstance(Arrays.asList("file1.xml", "file2.xml"));
    }
}

And then your application code could inject the list by name like this:

public class SampleClass {
    private final List<String> files;

    @Inject
    public SampleClass(@Named("FilesToProcess") List<String> files) {
        this.files = files;
    }
}
hallidave
+1  A: 

I agree with Dave Stenglein for runtime values.

There are frameworks like Obix that are specialized in the configuration. I like Guice for code injection, but they are better for that configuration injection.

Banengusk