popcoder
popcoder

Reputation: 3070

Injecting objects with Guice 3.0

I've just started using Guice and having trouble with understanding the guice way of injection. I'm very familiar with Spring, but this seems a bit different.

I have a DAO class:

public class SomeDAO {
    @NotNull
    private DB db = null;

    public SomeDAO (String databaseName) throws Exception{
        xxxxxxxxxxxxxxxxxxxxxxxx
    }
}

I have a controller, say:

public class SomeController {
    private SomeDAO someDAO;
}

How should i use guice here to inject someDAO object? Note that the databaseName in SomeDAO constructor should be provided from SomeController.

Thanks.

Upvotes: 0

Views: 201

Answers (1)

condit
condit

Reputation: 10962

Ideally SomeController shouldn't have to know the name of the database. This would come from a configuration file or from your application context and you'd inject your DAO like this:

public class SomeController {
  private final SomeDAO someDAO;

  @Inject 
  SomeController(SomeDAO someDAO) {
    this.someDAO = someDAO;
  }
}

And then to inject the database name you could do something like this:

public class SomeDAO {

  @NotNull
  private DB db = null;

  @Inject
  public SomeDAO (@IndicatesDatabaseName String databaseName) throws Exception {
    ...
  }
} 

In this case Guice will provide databaseName (see https://code.google.com/p/google-guice/wiki/BindingAnnotations). If you want to give the controller knowledge of the database name then you could consider just newing the DAO from the controller (but still injecting the controller) or using assisted inject.

EDIT:

If the controller really needs to know about the database you could use assisted inject:

public class SomeController {

  private final SomeDAO someDAO;

  @Inject
  SomeController(@Assisted String databaseName) {
    this.someDAO = new SomeDAO(databaseName);
  }
}
public interface ControllerFactory {
  public SomeController create(String databaseName);
}
public static class MyModule extends AbstractModule {
  @Override
  protected void configure() {
    install(new FactoryModuleBuilder()
    .implement(SomeController.class, SomeController.class)
    .build(ControllerFactory.class));
  }
}

And then inject ControllerFactory where SomeController is needed. You could apply the same assisted injection to SomeDAO if it ends up needing more injected dependencies, as well.

Upvotes: 4

Related Questions