0

我有一个通用 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 时,我工作。

4

2 回答 2

0

试试这个

    String userDir = System.getProperty("user.dir");
    File file =  new File(userDir+"/lib/db2.xml");
于 2012-11-23T05:16:00.970 回答
0

db2.xml 应该在类路径中。告诉我们您是如何运行 Java 应用程序的。如果您使用 ide 之类的 eclipse,请将 lib 目录添加到类路径(构建路径)。如果您使用的是纯 java 命令,则使用以下命令在类路径中包含 lib 目录。

java -cp {path to lib directory},{what ever jars you have comma seperated} mainClass

此外,默认情况下,java 命令在类路径中不会有当前目录。

于 2012-11-23T05:36:40.597 回答