[英]Is there any way to add hibernate.cfg.xml and log4j.properties file from custom folder while running tasks from ant
[英]How to Access hibernate.cfg.xml, config.properties, and log4j.properties from outside project folder
我想將我的Java項目(使用eclipse)導出到可執行jar中,但是我希望將來可以對hibernate.cfg.xml,config.properties和log4j.properties進行編輯,因此如何使hibernate從項目文件夾或任何外部文件訪問該文件使該文件可編輯以備將來使用的另一種方法,
我已經嘗試從外部項目文件夾訪問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仍然一無所知,任何幫助都將是很高興的:)
我有解決您問題的方法:
config.properties
您可以將配置文件通過參數-DconfigurationFile
設置為JVM。 然后嘗試在您的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
我不知道該怎么做。 無論如何,發布后配置持久性很困難,因為配置很難綁定到實現上。 我認為可以將其保留在classpath中。
您可以指示休眠從文件系統中加載配置文件,
有很多重載的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);
對於log4j,您可以在log4j配置文件中提供-D參數
像-Dlog4j.configuration={path to .properties or .xml }
log4j外部化的類似問題: 如何正確初始化log4j?
值得一讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.