Accessing the application.conf properties from jav

2019-02-01 04:30发布

问题:

I want to add an object to the Global scope, and in order to construct it I need to pass it a path to a file. I don't want to hard code the file path in the source, and so I want to get that path from the application.conf.

The problem is that I don't know how to access these properties from the java class. I tried this:

Configuration.root().getString("file.path")

But it ends with a NullPointerException.

Am I wrong in assuming that there's a global Configuration instance that I can use? Thanks.

回答1:

Try Play.application().configuration().getString("your.key")

As noted in the comment (nico_ekito), please use play.Play and not play.api.Play. play.api.Play is for scala controllers (see comment by Marcus biesior Biesioroff)

Additionally, play uses https://github.com/typesafehub/config under the hood so it can also provide some insights.



回答2:

Even if it seems simple, here is the scala way to get properties from configuration file :

Play 2.0 and 2.1 :

import play.api.Play.current
...
Play.application.configuration.getString("your.key")

Play 2.2 and +

import play.api.Play.current
...
current.configuration.getString("your.key")

Using Typesafe config

import com.typesafe.config.ConfigFactory
...
ConfigFactory.load().getString("your.key");


回答3:

From Play 2.4 and + it is better to use dependency injection to access Configurations:

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


@Inject
private Configuration configuration;

...

String value = configuration.getString("your.key");


回答4:

Since Play 2 uses the Typesafe config library, I accessed my vars in application.conf like this :

ConfigFactory.load().getString("my.var");


回答5:

In the play java is:

import play.Play;
...
Play.application().configuration().getString("key")


回答6:

Use as following (Tested in Play 1.2.5)

${play.configuration.getProperty('my.var')}

where my.var should be specified in application.conf file



回答7:

As a reference to access it from the template (for play < 2)

play.configuration['your.key']


回答8:

As folks have mentioned, Play.application.configuration no longer exists.

In Play Scala 2.3.x, to read a value from conf/application.conf, you can do the following:

import play.api.Play.current
...
current.configuration.getString("key")


回答9:

In Play 1.2.x

import play.Play;
...


String version  = Play.configuration.getProperty("application.version.number", "1.1.1");

where the second parameter is the default value



回答10:

Import this

import com.typesafe.config.Config;

and write the below lines

private Config config;
this.config = ConfigProvider.config();
String value = this.config.getString("fieldFromConfigFile");


回答11:

import play.Play; String myVal = Play.configuration.getProperty("your.key").toString();

i use this in my app and it works

Dont forget to import play.Play. Hope it'll gives you help