我编写了一个Spring程序,其中以下类,接口和xml文件位于不同的包中。我使用Eclipse Kepler。
package com.rajeev.spring.action;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.rajeev.spring.DAOI.Select;
/**
* @author rajeev
*
*
*/
public class SelectClient {
/**
* @param args
*/
public static void main(String[] args) {
String path=System.getProperty("user.dir");
System.out.println(path+"/src/com/rajeev/spring/DAOImpl/SelectCfg.xml");
Resource resource=new ClassPathResource(path+"/src/com/rajeev/spring/DAOImpl/SelectCfg.xml");
XmlBeanFactory beanFactory=new XmlBeanFactory(resource);
Object object=beanFactory.getBean("sb");
Select select=(Select)object;
System.out.println("emp name is:"+select.fetchName(101));
}
}
问题在于,当我执行SelectClient.java
时,它会发出以下错误
E:\javahyd\eclipse\Spring_DataSource_Object_Inject/src/com/rajeev/spring/DAOImpl/SelectCfg.xml Jan 17, 2014 11:41:43 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [E:/javahyd/eclipse/Spring_DataSource_Object_Inject/src/com/rajeev/spring/DAOImpl/SelectCfg.xml] Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [E:/javahyd/eclipse/Spring_DataSource_Object_Inject/src/com/rajeev/spring/DAOImpl/SelectCfg.xml]; nested exception is java.io.FileNotFoundException: class path resource [E:/javahyd/eclipse/Spring_DataSource_Object_Inject/src/com/rajeev/spring/DAOImpl/SelectCfg.xml] cannot be opened because it does not exist at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.springframework.beans.factory.xml.XmlBeanFactory.(XmlBeanFactory.java:78) at org.springframework.beans.factory.xml.XmlBeanFactory.(XmlBeanFactory.java:66) at com.rajeev.spring.action.SelectClient.main(SelectClient.java:26) Caused by: java.io.FileNotFoundException: class path resource [E:/javahyd/eclipse/Spring_DataSource_Object_Inject/src/com/rajeev/spring/DAOImpl/SelectCfg.xml] cannot be opened because it does not exist at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) ... 4 more
以上异常,是由于路径。当我在run(windows + r)中使用相同的路径时,它会打开特定的文件。我不希望将配置文件保留在任何软件包之外。
答案 0 :(得分:1)
ClassPathResource
用于引用类路径中资源的路径。 path
中传递的ClassPathResource
参数指的是类路径中的绝对路径。所以,使用
Resource resource=new ClassPathResource("com/rajeev/spring/DAOImpl/SelectCfg.xml");
尝试使用FileSystemResource
提及文件系统中的绝对路径
答案 1 :(得分:-1)
使用FileSystemResource而不是ClassPathResource资源并提供完整路径,例如Resource resource=new FileSystemResource("C://path/to//your//config.xml");