java - 如何从外部项目文件夹访问 hibernate.cfg.xml、config.properties 和 log4j.properties

标签 java xml eclipse hibernate

我想将我的java项目(使用eclipse)导出到可执行jar中, 但我希望 hibernate.cfg.xml、config.properties 和 log4j.properties 可供将来编辑, 那么如何使 hibernate 从外部项目文件夹访问该文件或以任何其他方式使该文件将来可编辑,

我尝试使用此代码从外部项目文件夹访问 hibernate.cfg.xml

SessionFactory sessionFactory = new Configuration().configure("mon/hibernate.cfg.xml").buildSessionFactory();

但是我收到了这个错误

mon/hibernate.cfg.xml not found
Exception in thread "main" java.lang.ExceptionInInitializerError

并且仍然不知道 config.properties 和 log4j.properties, 任何帮助都会很高兴:)

最佳答案

我的解决方案可以解决您的问题:

config.properties

您可以通过设置为 JVM 的参数 -DconfigurationFile 来定义配置文件。然后尝试在您的classpath(jar内)中查找confiFile,如果找不到,则将搜索文件系统。好吧,最后属性将被 JVM 参数覆盖。

Properties prop = new Properties();
String configFile = System.getProperty("configurationFile",defaultConfigurationFile);
    try {
      InputStream classPathIo = getClass().getClassLoader().getResourceAsStream(configFile);
      if(classPathIo != null) {
        prop.load(classPathIo);
      } else {
        prop.load(new FileReader(configFile));
    } catch (FileNotFoundException e) {
      log.warn("The config file {} cannot be found. It can be setup by -DconfigurationFile parameter.",configFile);
    } catch (IOException e) {
      log.warn("The config file {} is not readable.",configFile);
    } finally {
      log.info("Configuration loaded! {} values found from configFile {}.",prop.entrySet().size(),configFile);
      prop.putAll(System.getProperties());
    }

log4j.properties

解决方案是使用以下 JVM 参数:

-Dlog4j.configuration={path to file}

如果文件不在类路径中(如果是 Tomcat,则位于 WEB-INF/classes 中),而是位于磁盘上的某个位置,请使用 file:,例如

-Dlog4j.configuration=file:/somewhere/on/disk/log4j.properties

hibernate.cfg.xml

我不知道该怎么做。无论如何,发布后很难配置持久性,因为配置与实现是硬绑定(bind)的。我认为将其保留在类路径中是可以的。

关于java - 如何从外部项目文件夹访问 hibernate.cfg.xml、config.properties 和 log4j.properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19444933/

相关文章:

java - 在两种不同方法之间传递字符串值

java - 如何阻止 Sun JDK1.6 内置 StAX 解析器解析 DTD 实体?

eclipse - tomcat 上的 java web 服务 (jersey) 仅在从 eclipse 运行时才有效

xml - XSD 中的字符串数组

java - Eclipse 崩溃后在 Tomcat 下运行 Java 项目的问题

java - Windows 与 Unix 运行相同 Java 代码时的性能差异

java - 使用非 Comparable 类 : why a run-time exception, 而不是编译时错误创建 TreeSet?

java - Mac 操作系统上的 Windows 批处理文件相当于什么?

Java CSV 文件操作

java - 将输入写入和读取到 xml