[英]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.