首页 > 解决方案 > 将 jar 文件中的属性文件外部化

问题描述

我有一个带有 application.properties 文件的 jar,如下所示-

BASE_ENVIRONMENT = http://localhost

这是我读取属性文件的实用程序类

        Properties prop = new Properties();
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        InputStream in = loader.getResourceAsStream(fileName + ".properties");

属性文件在<default package>

这个 jar 在我的 Web 应用程序中用作依赖 jar,该应用程序部署在tomcat server.

但我需要更改BASE_ENVIRONMENT生产环境。

有没有办法可以将此属性文件值外部化?

标签: javamaventomcat

解决方案


您可以添加一个系统参数作为配置文件:

 // default to DEV
 String profile = "dev"
 if (System.getProperty("ENV") != null) {
    profile = System.getProperty("ENV");
 }
 Properties prop = new Properties();
 ClassLoader loader = Thread.currentThread().getContextClassLoader();
 InputStream in = loader.getResourceAsStream(fileName + "_" + profile + ".properties");

然后你会开始你的应用程序

   .... -DENV=prod

并且像 config_prod.properties 这样的文件会在类路径中找到,默认为 config_dev.properties。


推荐阅读