Spring加载配置文件的几种方法(org.springframework.beans.factory.BeanDefinitionStoreException)

一: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 );

 

posted @ 2015-07-11 10:11  我的名字叫浩仔丶  阅读(1047)  评论(0编辑  收藏  举报