Reputation: 3468
Let's say I have a class A in a jar in my class-path (i.e., I have no control over its source and thus cannot simply annotate it with @Inject
). A has the following constructor definition:
A(B b, C c) {
this.b = b;
this.c = c;
}
In my code base, I have classes:
BImpl implements B
and
CImpl implements C
My question is: How do I configure Guice to manage instances of A to be injected with BImpl and CImpl (if it is even within the scope of the framework)?
Upvotes: 1
Views: 536
Reputation: 66263
When you say "a class A in a jar file" I assume you have no control over the source of that class - you cannot simply add @Inject
to the constructor.
If that is the case, then you can define a Module
like this:
class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(B.class).to(BImpl.class);
bind(C.class).to(CImpl.class);
try {
bind(A.class).toConstructor(A.class.getConstructor(B.class, C.class));
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
The first two bindings are standard - you bind the interface types to the implementation types.
The last binding uses toConstructor
(since Guice 3.0), which allows you to "glue" foreign components more easily - just as in your case.
Upvotes: 1