[英]How can a Java class in a Jar read a external XML configuration file?
我得到了一个通用jar,用于使用数据源XML配置'db2.xml'创建数据库连接池,它位于此JAR的相同路径下,例如:
Project/
-- lib
-- db2.xml
-- common.jar
遵循用于读取db2.xml的代码:
private BeanFactory() {
try {
beanFactory = new DefaultListableBeanFactory();
xmlReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry)
beanFactory);
resource = new ClassPathResource("db2.xml");
xmlReader.loadBeanDefinitions(resource);
} catch (Exception e) {
e.printStackTrace();
}
}
总是会发生错误:
org.springframework.beans.factory.BeanDefinitionStoreException: IOException
parsing XML document from class path resource [db2.xml]; nested exception is
java.io.FileNotFoundException: class path resource [db2.xml] cannot be opened
because it does not exist
因此它一定是由于找不到“ db2.xml”引起的。 是否设置配置文件resource = new ClassPathResource("/db2.xml")
或resource = new ClassPathResource("lib/db2.xml")
或resource = new ClassPathResource("../lib/db2.xml")
; 我全都不工作。 我如何为此设置相对路径。
resource = new ClassPathResource(CONFIGURATION_PATH);
这是一个Java项目。 当我将db2.xml放入通用jar时,我可以工作。
尝试这个
String userDir = System.getProperty("user.dir");
File file = new File(userDir+"/lib/db2.xml");
db2.xml应该在类路径中。 告诉我们您如何运行Java应用程序。 如果您使用的是eclipse之类的ide,请将lib目录添加到classpath(build path)。 如果使用纯java命令,则使用以下命令在类路径中具有lib目录。
java -cp {path to lib directory},{what ever jars you have comma seperated} mainClass
同样,默认情况下,java命令在classpath中不会有当前目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.