Guice:绑定非直接依赖项

时间:2014-11-28 22:43:21

标签: java dependency-injection guice

以下是我的课程:

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

因此,这需要注入MyServiceMyServiceImpl个实例的请求。但我无法弄清楚如何告诉Guice使用MyServiceImpl配置MyCommandImpl,以及如何将MyCommandImplMyDAOImpl绑定。

1 个答案:

答案 0 :(得分:3)

您需要的其他绑定和注射应该像第一个一样进行设置。在需要实例的地方使用@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();
    }
}