Spring中的几种容器都支持使用xml装配bean,包括:
XmlBeanFactory ,
ClassPathXmlApplicationContext ,
FileSystemXmlApplicationContext ,
XmlWebApplicationContext
加载这些容器的配置文件的xml有一下几种常见的方法:
1:引用资源用XmlBeanFactory(不能实现多个文件相互引用)
Resource resource = new ClassPathResource("appcontext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
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 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");
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);
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 );
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext );
文章转载: