Inject MongoDB instance in Play Framework [java]

Trying to figure out how to connect to MongoDB in the Play JAVA Framework (version 2.4x) using the built-in DI framework, Guice.

So far I am using Jongo (version 1.2). I create a JongoProvider class where I initialize the MongoDB instance with the appropriate IP address for MongoDB, etc.

I inject this into the model as shown below ... however it seems that I cannot access the injected instance in the static method. Is there a proper way to access the Mongo injection object?

class User {
    @Inject JongoProvider jongo;

    public static User getUsers() {
        // can't access static instance
        jongo.getcollection("users");
    }
}

// === Edit based on Mon Calamari's answer

class User {

    public static JongoProvider jongo() {
        return Play.application().injector().instanceOf(JongoProvider.class);
    }

    public static User getUsers() {
        jongo().getcollection("users");
    }
}
+4
source share
1 answer

User Guice, Guice -, Guice . Play:

JongoProvider provicer = Play.application().injector().instanceOf(JongoProvider.class)
0

Source: https://habr.com/ru/post/1598630/


All Articles