Spring加载配置文件的几种方法(出现错误的时候可以查看)

来源:互联网 发布:大数据商务拓展怎么做 编辑:程序博客网 时间:2024/04/30 17:31
javax.servlet.ServletException: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [D:\Program Files\apache-tomcat-6.0.26\bin\WebContent\WEB-INF\config\spring\web-application-config.xml]; nested exception is java.io.FileNotFoundException: WebContent\WEB-INF\config\spring\web-application-config.xml (The system cannot find the path specified)
 
如果改为:
ApplicationContext ctx=new     ClassPathXmlApplicationContext("WebContent/WEB-INF/config/spring/web-application-config.xml");
又会报错:
javax.servlet.ServletException: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [WebContent/WEB-INF/config/spring/web-application-config.xml]; nested exception is java.io.FileNotFoundException: class path resource [WebContent/WEB-INF/config/spring/web-application-config.xml] cannot be opened because it does not exist

这是因为调用的是ClassPathXmlApplicationContext,而WebContent/WEB-INF/config/spring/web-application-config.xml并不在classespath路径中。

可见是加载ApplicationContext的方法有问题,那么,我们来查下加载spring配置文件有几种方法:

一:Spring中的几种容器都支持使用xml装配bean,包括:
XmlBeanFactory ,
ClassPathXmlApplicationContext ,
FileSystemXmlApplicationContext ,
XmlWebApplicationContext
加载这些容器的配置文件的xml有一下几种常见的方法:
1:引用资源用XmlBeanFactory(不能实现多个文件相互引用)
Resource resource = new ClassPathResource("appcontext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
从factory中获取相应资源文件中的bean,但是这种bean读不到引用了其他文件中的bean!
2:引用应用上下文用ClassPathXmlApplicationContext
ApplicationContext factory=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
ApplicationContext factory=new ClassPathXmlApplicationContext("conf/userConfig.xml"); // src/conf 目录下的 
ApplicationContext factory=new ClassPathXmlApplicationContext("file:G:/Test/src/appcontext.xml");
3:用文件系统的路径引用应用上下文用FileSystemXmlApplicationContext
ApplicationContext factory=new FileSystemXmlApplicationContext("src/applicationContext.xml"); 
ApplicationContext factory=new FileSystemXmlApplicationContext("classpath:appcontext.xml");
ApplicationContext factory=new FileSystemXmlApplicationContext("file:G:/Test/src/appcontext.xml");
ApplicationContext factory=new FileSystemXmlApplicationContext("G:/Test/src/appcontext.xml");
注意:在2、3的加载方式中可以加载多个配置文件,获取到ApplicationContext 对象中
String[] configs = {"applicationContext.xml","user_spring.xml"};
ApplicationContext ctx = new ClassPathXmlApplicationContext(configs);
//ApplicationContext ctx=new FileSystemXmlApplicationContext(configs);
AbstractDao myUserDAO = (AbstractDao) ctx.getBean("userDao");
4:Web工程定制的加载方法 XmlWebApplicationContext
ServletContext servletContext = request.getSession().getServletContext(); 
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext );


 

0 0
原创粉丝点击