Reputation: 56894
Here are my classes:
public interface MyService {
// ...
}
public class MyServiceImpl implements MyService {
private MyCommand myCommand;
}
public interface MyCommand {
// ...
}
public class MyCommandImpl implements MyCommand {
private MyDAO myDAO;
}
public interface MyDAO {
// ...
}
public class MyDAOImpl implements MyDAO {
// ...
}
public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(MyService.class).to(MyServiceImpl.class)
}
}
public class MyDriver {
@Inject
private MyService myService;
public static void main(String[] args) {
MyModule module = new MyModule();
Injector injector = Guice.createInjector(module);
MyDriver myDriver = injector.getInstance(MyDriver.class);
// Should have been injected with a MyServiceImpl,
// Which should have been injected with a MyCommandImpl,
// Which should have been injected with a MyDAOImpl.
myDriver.getMyService().doSomething();
}
}
So this takes care of injecting requests for MyService
s with instances of MyServiceImpl
. But I can't figure out how to tell Guice to configure MyServiceImpl
s with MyCommandImpl
, and how to bind MyCommandImpl
s with MyDAOImpl
s.
Upvotes: 0
Views: 104
Reputation: 5867
The other bindings and injections you need should be set up just like the first one. Use @Inject
wherever the instance is needed, and bind
the interface to an impl in your module. I've added 4 lines below (annotated 2 injection sites and defined 2 more bindings):
public interface MyService {
// ...
}
public class MyServiceImpl implements MyService {
@Inject
private MyCommand myCommand;
}
public interface MyCommand {
// ...
}
public class MyCommandImpl implements MyCommand {
@Inject
private MyDAO myDAO;
}
public interface MyDAO {
// ...
}
public class MyDAOImpl implements MyDAO {
// ...
}
public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(MyService.class).to(MyServiceImpl.class);
bind(MyCommand.class).to(MyCommandImpl.class);
bind(MyDAO.class).to(MyDAOImpl.class);
}
}
public class MyDriver {
@Inject
private MyService myService;
public static void main(String[] args) {
MyModule module = new MyModule();
Injector injector = Guice.createInjector(module);
MyDriver myDriver = injector.getInstance(MyDriver.class);
// Should have been injected with a MyServiceImpl,
// Which should have been injected with a MyCommandImpl,
// Which should have been injected with a MyDAOImpl.
myDriver.getMyService().doSomething();
}
}
Upvotes: 3