2013-10-18 150 views
0

我想將我的java項目(使用eclipse)導出到可執行文件夾, 但我想要hibernate.cfg.xml,config .properties和log4j.properties可編輯爲將來, 所以如何使Hibernate從外部項目文件夾訪問該文件或任何其他方式來使該文件可編輯爲未來,如何從外部項目文件夾訪問hibernate.cfg.xml,config.properties和log4j.properties

我已經嘗試此代碼的acces 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, 任何幫助將是快樂:)

回答

1

有我的解決問題的方法思路:

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} 

如果文件不在類路徑(在WEB-INF /類)但在你的磁盤上某處,使用文件:,如

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

hibernate.cfg.xml

我不知道該怎麼做。無論如何,很難在發佈之後配置持久性,因爲配置很難綁定到實現。我認爲可以將它保存在classpath中。

+0

我很抱歉,我以前從未使用過JVM參數...我是否爲此代碼創建了一個新文件-Dlog4j.configuration = file:/ somewhere/on/disk/log4j.properties'或者我擁有哪個文件添加此代碼? –

+0

你如何運行代碼? Stnadalone?像Tomcat這樣的容器? –

+0

我只是做一個Java項目不是Web項目或其他...在未來,這個Java將運行在命令提示符(可執行jar)與此命令'java -jar '任何想法? –

0

您可以指示休眠加載從文件系統配置文件,

有很多重載configure()方法可用,看到的鏈接文件建立

以下是你可以做的方式:

File conf = new File(ABS_PATH_TO_CONFIG+File.separator+"hibernate.cfg.xml"); 
Configuration configuration = new Configuration().configure(conf.getAbsoluteFile()); 

ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); 
sessionFactory = configuration.buildSessionFactory(serviceRegistry); 

http://docs.jboss.org/hibernate/orm/3.6/javadocs/org/hibernate/cfg/Configuration.html#configure(java.io.File)

和log4j的,你可以給使用日誌-D參數4J配置文件

像log4j的外在-Dlog4j.configuration={path to .properties or .xml }

類似的問題:How to initialize log4j properly?

這將是值得一讀這一點。

+0

我很抱歉,我仍然沒有得到它......我必須添加此代碼的文件'File conf = new File(ABS_PATH_TO_CONFIG + File.separator +「hibernate.cfg。 XML「);配置(conf.getAbsoluteFile());'到我的控制器或DBUtil? –

+0

注意:我的意思是HibernateUtil〜 –

+0

@splatter_fadli:編輯ans,把這個地方建立你的sessionfactory –

相關問題