Dependency injection using Guice with the DAO pattern

后端 未结 1 1599
一生所求
一生所求 2021-01-21 14:59

For a small side project I\'m working on I\'ve been trying to implement something of a DAO pattern for my interactions with the DB, and have started using Guice (for my first ti

相关标签:
1条回答
  • 2021-01-21 15:28

    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.

    0 讨论(0)
提交回复
热议问题