gpt4 book ai didi

java - Guice:绑定(bind)非直接依赖项

转载 作者:行者123 更新时间:2023-12-01 22:33:39 25 4
gpt4 key购买 nike

这是我的类(class):

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

因此,这负责使用 MyServiceImpl 实例注入(inject)对 MyService 的请求。但我不知道如何告诉 Guice 使用 MyCommandImpl 配置 MyServiceImpl,以及如何将 MyCommandImplMyDAOImpl 绑定(bind)s。

最佳答案

您需要的其他绑定(bind)和注入(inject)应该像第一个一样设置。在需要实例的地方使用 @Inject,并将接口(interface)绑定(bind)到模块中的 impl。我在下面添加了 4 行(注释了 2 个注入(inject)位点并定义了另外 2 个绑定(bind)):

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

关于java - Guice:绑定(bind)非直接依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27196809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com