简体   繁体   中英

How can a Java class in a Jar read a external XML configuration file?

I got a common jar that used for creating Database Connection Pool with the datasource XML configuration 'db2.xml', which is under the same path of this JAR, like:

Project/
       -- lib
              -- db2.xml
              -- common.jar

Following the code for reading the 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();
            }
        }    

Always error happens:

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

So it must be caused by 'db2.xml' cannot be found. Whether configuration file are set resource = new ClassPathResource("/db2.xml") or resource = new ClassPathResource("lib/db2.xml") or resource = new ClassPathResource("../lib/db2.xml") ; I t all dose not work. How do I set a relative path for this.

resource = new ClassPathResource(CONFIGURATION_PATH);

This is a Java project. I works when I put the db2.xml into the common jar.

Try this

    String userDir = System.getProperty("user.dir");
    File file =  new File(userDir+"/lib/db2.xml");

db2.xml should be in classpath. tell us how you are running the java application. If you are using ide like eclipse, add the lib directory to classpath(build path). If you are using plain java command , then use following command to have lib directory in classpath.

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

Also by default java command wont have current directory in classpath.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM