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

前端 未结 13 2061
一整个雨季
一整个雨季 2020-12-24 10:37

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

相关标签:
13条回答
  • 2020-12-24 10:50

    Starting from version 2.5 please use play.Application class which should be injected and then application.config().getString("your.property.here")

    0 讨论(0)
  • 2020-12-24 10:51

    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.

    0 讨论(0)
  • 2020-12-24 10:54

    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");
    
    0 讨论(0)
  • 2020-12-24 10:57

    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

    0 讨论(0)
  • 2020-12-24 10:57

    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");
    
    0 讨论(0)
  • 2020-12-24 11:00

    In the play java is:

    import play.Play;
    ...
    Play.application().configuration().getString("key")
    
    0 讨论(0)
提交回复
热议问题