Java – play 2.5 3: Use dependency injection to get configuration values

I tried to migrate a play framework application from 2.4 to 2.5 3, and I have questions from application Conf file get value:

From application Conf gets a value. What I do is:

Play.application().configuration().getString("label")

Now, due to play Application () has been deprecated. I should use dependency injection According to the framework documentation, I use the following instructions:

>Define import: import javax inject.*; Import play Configuration; > Define class attributes: @ inject private configuration; > Use configuration class properties on my class

When I follow my controller application These instructions on Java show that it works normally:

But when I try to use it from another class object in my project, dependency injection doesn't work. I always get a NullPointerException

Someone can give me a on how to use dependency injection from application Conf get value example?

Part of my java code, I tried to use Di:

import javax.inject.Inject;
import play.Configuration;
import play.Logger;

public class Zipper {

    @Inject private  Configuration configuration;

    public void unZip(String zipFilePath) {
        Logger.debug("Display : zipFilePath"+zipFilePath);
        Logger.debug("before call parameter from application.conf");
        Logger.debug("configuration.getString = "+configuration.getString("Unzipedfile.path"));
        Logger.debug("aftercall parameter from application.conf");
    }
}

And I always get a null pointer exception with configure On the line of getString ("unzipedfile. Path")

Solution

I think you can initialize the configuration as follows:

private  Configuration configuration = Play.current().injector().instanceOf(Configuration .class);

So your zipper will be:

import javax.inject.Inject;
import play.Configuration;
import play.Logger;

public class Zipper {

    private  Configuration configuration = Play.current().injector().instanceOf(Configuration .class);

    public void unZip(String zipFilePath) {
        Logger.debug("Display : zipFilePath"+zipFilePath);
        Logger.debug("before call parameter from application.conf");
        Logger.debug("configuration.getString = "+configuration.getString("Unzipedfile.path"));
        Logger.debug("aftercall parameter from application.conf");
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>