I am a complete beginner with Guice, and trying to achieve the following:
public class Apple {
private final Integer size;
public Apple(Integer size) {
this.size = size;
}
}
public abstract class AppleModule {
protected AppleModule() {
ImmutableSet<Integer> sizes = ImmutableSet.of(1, 2, 3);
ImmutableSet<Apple> apples = sizes.stream().map(Apple::new).collect(ImmutableSet.toImmutableSet());
bind(new ImmutableSet<Apple>(){}).toInstance(apples);
}
}
so that every time I declare something like ImmutableSet<Apple> apppleBasket;
, I get the same list object injected. (but ImmutableSet
s of other types still behave as normal)
But code above does not work with bind(...)
saying Class must either be declared abstract or implement abstract method error
Note: I simplified the code I'm working on quite a bit while writing the question, so above might not compile out of box.
First of all, a Guice
module has to extend the AbstractModule
class and override its configure()
method. Second of all, if you want to bind generic types, you need to use TypeLiteral.
public class AppleModule extends AbstractModule {
@Override
public void configure() {
ImmutableSet<Integer> sizes = ImmutableSet.of(1, 2, 3);
ImmutableSet<Apple> apples = sizes.stream().map(Apple::new)
.collect(ImmutableSet.toImmutableSet());
bind(new TypeLiteral<ImmutableSet<Apple>>(){}).toInstance(apples);
}
}
Or, for example, you can use a @Provides
method.
@Provides
ImmutableSet<Apple> provideAppleBasket() {
ImmutableSet<Integer> sizes = ImmutableSet.of(1, 2, 3);
ImmutableSet<Apple> apples = sizes.stream().map(Apple::new)
.collect(ImmutableSet.toImmutableSet());
return apples;
}
Please, use Guice documentation for additional information.