Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the application.conf properties from java class with Play! 2.0

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.

like image 262
Nitzan Tomer Avatar asked Mar 23 '12 18:03

Nitzan Tomer


People also ask

Where do I put application conf?

conf file that defines the defaults. you can add an application. conf file in the classpath (or an absolute path, or an URL). It only needs to contain the options that you override.

What is application conf file?

An application configuration file is an XML file used to control assembly binding. It can redirect an application from using one version of a side-by-side assembly to another version of the same assembly. This is called per-application configuration.

What is Typesafe config?

Typesafe Config allows you to store configuration into separated files and use include keyword to include configuration of those files. Here is a concrete example for myApp which relies on the configuration of moduleA and moduleB .


2 Answers

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.

like image 94
Nasir Avatar answered Sep 20 '22 04:09

Nasir


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"); 
like image 44
i.am.michiel Avatar answered Sep 19 '22 04:09

i.am.michiel