IAmYourFaja
IAmYourFaja

Reputation: 56894

Guice: binding non-immediate dependencies

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 MyServices with instances of MyServiceImpl. But I can't figure out how to tell Guice to configure MyServiceImpls with MyCommandImpl, and how to bind MyCommandImpls with MyDAOImpls.

Upvotes: 0

Views: 104

Answers (1)

The111
The111

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

Related Questions