这是我的课程:
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();
}
}
因此,这负责将MyService
的请求注入MyServiceImpl
实例。但是我不知道如何告诉 Guice 用 MyCommandImpl
配置 MyServiceImpl
s,以及如何将 MyCommandImpl
s 与 MyDAOImpl
s 绑定。
您需要的其他绑定和注入应该像第一个一样设置。 在需要实例的任何位置使用 @Inject
,并将接口bind
到模块中的 impl。 我在下面添加了 4 行(注释了 2 个注入位点并定义了另外 2 个绑定):
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();
}
}