java - Web 应用程序中的属性文件

标签 java configuration properties

首先,有很多解决方案,我已经阅读了很多。但出于某种原因,我没有让它工作。

我正在尝试为我的 webapp 外包我的配置数据,以便我可以在部署后对其进行修改。

这是我的属性服务:

   public class PropertiesService {

 Properties properties;
     public PropertiesService() {
      try {
       properties = new Properties();
       ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
       InputStream stream = classLoader.getResourceAsStream("META-INF/config.properties");
       properties.load(stream);
      } catch (Exception e) {
       e.printStackTrace();
      }
     }

     public String getHost(){
      return properties.getProperty("server_host");
     }

     public String getServerName(){
      return properties.getProperty("server_naming");
     }
    }

调试后我注意到变量流仍然为空!但是不知道为什么-.-

需要帮助:-)

这里是错误日志:

java.lang.NullPointerException
 at java.util.Properties$LineReader.readLine(Properties.java:418)
 at java.util.Properties.load0(Properties.java:337)
 at java.util.Properties.load(Properties.java:325)

更新

我现在执行以下操作:

properties.load(this.getClass().getResourceStream("/config/config.properties"));

我仍然得到一个 nullPointerException

最佳答案

META-INF中取出,放在src/config中,直接到source中的config包,build后会到/WEB-INF/classes/config/config.properties

this.getClass().getResourceAsStream("/config/config.properties");

更新 enter image description here

然后我在同一个项目中创建了一个 Service 类,它有一个方法。

public static InputStream getConfigAsInputStream(){
    return Service.class.getResourceAsStream("/config/config.properties");
}

这有效..!!

比较你的

关于java - Web 应用程序中的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4814506/

相关文章:

java - LibGDX - Scene2d 无法单击小部件

java - 在 Libgdx 库中使用 getSpectrum()

java - 在java中处理特定于环境的配置的最佳方法是什么?

configuration - 限制特定用户对站点公共(public)页面的访问

java - @Value注释语法问题

java - 无法在Gradle的JavaExec任务中设置命令行参数

用于 LDAP 身份验证的 ASP.NET MVC : How to setup web. 配置?

python - 列出 python 类中的 @property 装饰方法

PHP 类 $_SERVER 变量一个属性

java - 无法创建名称为 Entry 的类