我得到的用於與數據源的XML配置「db2.xml」,這是該JAR的同一路徑下,如創建數據庫連接池常見的罐子:Jar中的Java類如何讀取外部XML配置文件?
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時,我工作正常。
在'lib'目錄中添加'db2.xml'沒有意義,仍然嘗試''classpath:lib/db2.xml「' –
這是什麼意思?使用「classpath:lib/db2.xml」替換「db2.xml」作爲配置路徑? –
你不能將單個文件添加到類路徑(除了罐子),你需要添加整個文件夾(如果你這樣做,我不會使用「lib」,因爲這會將所有jar文件添加兩次)。 – Thilo