【问题标题】:Spring Boot - Identify resources under resource folderSpring Boot - 识别资源文件夹下的资源
【发布时间】:2017-03-13 21:32:23
【问题描述】:

我有一个 Spring Boot 应用程序。我正在尝试阅读我放在 main/resources 文件夹下的几个文件。我看到 Spring Boot 会自动读取资源文件夹下的 application.properties。但是,它似乎没有读取我放在资源文件夹下的其他 xml/文本文件。

Source xslt = new StreamSource(new File("removeNs.xslt"));

我是否应该为程序添加任何其他配置以自动读取资源文件夹下的所有文件而无需显式提供路径?

【问题讨论】:

    标签: java spring-boot


    【解决方案1】:
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("removeNs.xslt").getFile());
    

    这应该可行。

    感谢 @Edwin 提到更强大的解决方案:

    File file = new File(Thread.currentThread().getContextClassLoader().getResource("removeNs.xslt").getFile());
    

    【讨论】:

    • 我建议使用Thread.currentThread().getContextClassLoader().getResource(),因为示例中的类加载技术有时会在应用程序上下文中失败。
    • @EdwinDalorzo 好建议。添加到答案中。
    • 感谢 EdwinDalorzo 和 Terry Li!
    【解决方案2】:

    您需要使用

    指定要读取资源文件夹下的特定文件

    @PropertySource 注释。

    您可以使用指定多个属性源

    @PropertySources({
        @PropertySource(),
        @PropertySource()
    })
    

    【讨论】:

      猜你喜欢
      • 2017-05-01
      • 2014-11-21
      • 2018-05-28
      • 1970-01-01
      • 2019-04-15
      • 2017-11-08
      • 2015-11-27
      • 2017-02-25
      • 1970-01-01
      相关资源
      最近更新 更多