Dependency injection using Guice with the DAO pattern

大城市里の小女人 提交于 2019-12-02 01:34:19

If you want an injection site like the following:

@Inject
public DAOConsumer(DAO<User> dao) {
}

to be injected with an instance of your UserDAO class then

bind(new TypeLiteral<DAO<User>>() {}).to(UserDAO.class);

is the correct syntax.

As for your other error:

1) No implementation for org.mongodb.morphia.Datastore was bound.

This is because Datastore is an interface. You need to bind the interface to an implementation, an instance, or a Provider<Datastore>.

To work out how to do this, think of the steps you would need to do this manually without the extra complication of Guice. Once you 100% understand this, you can try and design an object graph that appropriately reflects the steps in the initialization of morphia.

To get you started, the morphia quick tour has a guide on how to get an instance of the Datastore object:

final Morphia morphia = new Morphia();

// tell Morphia where to find your classes
// can be called multiple times with different packages or classes
morphia.mapPackage("org.mongodb.morphia.example");

// create the Datastore connecting to the default port on the local host
final Datastore datastore = morphia.createDatastore(new MongoClient(), "morphia_example");
datastore.ensureIndexes();

From their code, you can see that there are at least two dependencies required to get the Datastore:

  1. A singleton Morphia
  2. A singleton MongoClient

You will have to write some code to set this up, possibly using Guice's Provider class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!