1、利用ClassPathXmlApplicationContext可以从CLASSPATH中读取xml文件(最常见的使用方式)
- ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
- UserDao dao = (UserDao)context.getBean("userDao");
下面就可以使用接口的对象调用相应的方法了,这里需要注意一点的是我们可以使用通配符来读取多个xml文件
new ClassPathXmlApplicationContext("applicationContext-*")
2、下面这种方式很少有人使用了(将多个配置文件使用String数组的形式表示)
- ClassPathXmlApplicationContext resource = new ClassPathXmlApplicationContext(new String[]{"applicationContext-ibatis-oracle.xml","applicationContext.xml","applicationContext-data-oracle.xml"}); BeanFactory factory = resource; UserDao userDao = (UserDao) factory.getBean("userDao");
3、利用ClassPathResource读取配置文件
- Resource cr = new ClassPathResource("applicationContext.xml");
- BeanFactory bf=new XmlBeanFactory(cr);
- UserDao userDao = (UserDao)bf.getBean("userDao");
4、利用FileSystemResource读取
- Resource rs = new FileSystemResource("D:/tomcat/webapps/wiscom/
- WEB-INF/classes/applicationContext.xml");
- BeanFactory factory = new XmlBeanFactory(rs);
- UserDao userDao = (UserDao )factory.getBean("userDao");
使用FileSystemResource读取xml文件需要注意的是:配置文件必须放在project直接目录下,或是写明绝对路径,否则就会抛出找不到文件的异常.
5、利用FileSystemXmlApplicationContext读取
- String[] path={"WebRoot/WEB-INF/applicationContext.xml",
- "WebRoot/WEB-INF/applicationContext_task.xml"};
- ApplicationContext context = new FileSystemXmlApplicationContext(path);