Swapnil B.
Swapnil B.

Reputation: 759

play 2.6.x environment dependency injection

I am trying to find the mode (Dev vs Prod) of my play application. I have injected Environment as below:

public class Sample{
    @Inject
    private play.Environment environment;

and I am invoking the method as show below:

    public void methodName(){
        if(environment.isDev()) {
            //do something
        }
    }
}

since the variable environment is uninitialized it throws a NullPointerException when I try to access it to call isDev() method.

How do I initialize the environment object? Any help would be much appreciated. Thanks a ton!

Upvotes: 0

Views: 183

Answers (1)

Igmar Palsenberg
Igmar Palsenberg

Reputation: 647

First, don't use field injection, it won't work in a lot of cases.

public class Sample {
    @Inject
    public Sample(final Environment environment) {

    }
}

Second, how is Sample created ? You need to create it using dependency injection, else it won't work. If you need it, use :

bind(Sample.class).as(Singleton.class);

and then @Inject sample in another class. If it's not a singleton, bind() it differently

Upvotes: 1

Related Questions