I'm trying to pass an object which has a runtime variable into an other object. How can I achieve this using Guice? I'm new to dependency injection.
I would like to create several A objects (the number of them is decided at runtime) and that many B objects that uses an A object. But first let's start with one object from both of them.
Thank you for your help.
public interface IA {
String getName();
}
public class A implements IA {
@Getter
protected final String name;
@AssistedInject
A(@Assisted String name) {
this.name = name;
}
}
public interface IAFactory {
IA create(String name);
}
public interface IB {
IA getA();
}
public class B implements IB {
@Getter
protected final IA a;
//...
// some more methods and fields
//...
@Inject
B(IA a) {
this.a = a;
}
}
public class MyModule extends AbstractModule {
@Override
protected void configure() {
install(new FactoryModuleBuilder()
.implement(IA.class, A.class)
.build(IAFactory.class));
bind(IB.class).to(B.class);
}
}
public class Main() {
public static void main(String[] args) throws Exception {
if(args.size < 1) {
throw new IllegalArgumentException("First arg is required");
}
String name = args[0];
Injector injector = Guice.createInjector(new MyModule());
IB b = injector.getInstance(IB.class);
System.out.println(b.getA().getName());
}
}
I think you are not exactly clear about this. So let me explain a little.
Firstly, you created a Factory which you will use to create instances of
A. You did that because Guice doesn't know the value of parametername.Now what you want is to create an instance of
Bwhich depends on instance ofA. You are asking Guice to give you an instance ofBbut how will Guice create an instance ofBwithout anA? You haven't binded any instance ofA.So to fix this issue you will either have to create an instance of
Bmanually.The way you can achieve it is by following.
Firstly, you will require a Factory for
BThen you need to make the following changes in your class
BNow in your
mainmethodAlso, don't forget to update your configure method and install B factory.
Note I am passing
namein class B. You can update IBFactory to takeIAas assisted parameter and then first create an instance ofIAoutside usingIAFactoryand pass the instance ofIAtoIBFactoryto create an instance ofIB