【问题标题】:How to use property file in play framework in java?如何在java的play框架中使用属性文件?
【发布时间】:2018-12-03 19:48:40
【问题描述】:

我是新手玩框架。我想知道如何在play框架中使用属性文件。

我的属性文件是,

conf/test.properties
name=kumar
framework=playframework

所以现在我想在我的控制器类 (Application.java) 中使用 test.properties。

请让我知道我需要执行哪些步骤。

【问题讨论】:

    标签: java playframework playframework-2.0


    【解决方案1】:

    conf/ 文件夹中的所有文件都会自动添加到您的类路径中。您应该能够像这样访问您的文件:

    Properties prop;
    try {
      prop = new Properties();
      InputStream is = this.getClass().getResourceAsStream("test.properties");
      prop.load(is);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    
    String name = prop.getProperty("name");
    String framework = prop.getProperty("playframework");
    

    注意:我没有测试过以上任何一个。

    更新:

    我刚刚意识到这个问题与Load file from '/conf' directory on Cloudbees 非常相似,但由于我的解决方案还包括如何访问文件中的属性,所以我将保持原样。

    此外,由于您的控制器方法很可能是静态的,因此上述可能无法编译。在我引用的答案中,他们建议使用 Play 提供的工具!:

    Play.application().resourceAsStream("test.properties")
    

    【讨论】:

    • Play.application 已被弃用。
    【解决方案2】:

    您可以通过以下方式访问 play 框架中的属性文件:

    val ConfigLoader = play.Play.application.configuration
      implicit val connector = ContactPoints(Seq(ConfigLoader.getString("cassandra.host"))).keySpace(ConfigLoader.getString("cassandra.keyspace"))
    

    【讨论】:

    • 抱歉,在您的示例中,不清楚如何提及文件名。 OP 有一个名为 test.properties 的文件。您在示例中在哪里使用它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 2016-10-06
    相关资源
    最近更新 更多