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());
}
}