我想将我的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/