【问题标题】:Loading Java Properties Files by Profile按配置文件加载 Java 属性文件
【发布时间】:2017-09-02 08:30:10
【问题描述】:

我想在 Java 代码中加载属性文件。 但我使用配置文件来配置 -Dspring.profiles.active=local 或 dev... 如何通过配置文件加载属性文件是这样的:

classpath:${spring.profiles.active}/test.properties

如何在 Java 代码中做到这一点? 我做了如下,但得到空值。

Properties prop = new Properties();
InputStream iStream = Helper.class.getClassLoader().getResourceAsStream("test.properties");
    try {
        prop.load(iStream);
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    } finally {
        try {
            iStream.close();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }

【问题讨论】:

  • 但是我使用 getResourceAsStream() 加载,它无法获取该文件
  • 好吧,你不能将profiles 的弹簧特性与普通文件加载混为一谈。该功能在 Spring Boot 中开箱即用,可以轻松利用(请参阅我在之前的评论中将其标记为重复的问题
  • 感谢您的建议。但是,我还没有解决我的问题。我不使用spring boot,我使用-Dspring.profiles.active=local在Tomcat上配置参数,但它无法通过getResourceAsStream()加载属性,InputStream仍然为空。我的属性文件在 src/main/resources/local/test.properties

标签: java spring spring-mvc resources load


【解决方案1】:

这是我们的一些工作代码:

String activeProfile = System.getProperty("spring.profiles.active");
InputStream workSpacesFIS = this.getClass().getClassLoader()
        .getResourceAsStream(activeProfile + "/customers.txt");
if (workSpacesFIS != null) { ...

【讨论】:

    【解决方案2】:

    按配置文件加载 Java 属性文件

    public Properties getProp() throws IOException {
            final Properties prop = new Properties();
            prop.load(TestService.class.getResourceAsStream("/application.properties"));
            String activeProfile = prop.getProperty("spring.profiles.active");
            prop.load(TestService.class.getResourceAsStream("/application-"+activeProfile+".properties"));
            return prop;
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      • 2011-06-14
      • 2012-08-26
      • 1970-01-01
      • 2011-02-27
      • 2020-07-11
      • 2017-05-06
      相关资源
      最近更新 更多