1. 从classpath路径下加载applicationContext.xml文件
Resource resource = new ClassPathResource("applicationContext.xml");
XmlBeanFactory bean = new XmlBeanFactory(resource);
BizInterface biz = (BizInterface)bean.getBean("beanid");
classpath相对于project的src。
2. 从文件系统中加载applicationContext.xml文件
Resource resource = new
FileSystemResource("E:\\proj\\applicationContext.xml");
XmlBeanFactory bean = new XmlBeanFactory(resource);
路径要正确。
3. 从输入流中加载applicationContext.xml文件
InputStream is = new FileInputStream("E:\\proj\\applicationContext.xml");
Resource resource = new InputStreamResource(is);
XmlBeanFactory bean = new XmlBeanFactory(resource);
这种方式是使用输入流类InputStream来加载Spring配置文件。InputStream因为是抽象类,不能直接实例化,通常使用其子类FileInputStream来获取一个文件流
文件系统与输入流加载有什么区别?为什么不直接用文件系统加载?
4. 基于多配置文件的加载
String[] configFile = {"applicationContext.xml"};
ApplicationContext ac = new ClassPathXmlApplicationContext(configFile);
BeanFactory bean = (BeanFactory)ac;
使用这种方式允许加载多个Spring配置文件,这里指定的文件路径是当前项目的classpath路径,相对于web应用下的WEB-INF\classes目录
回家需要测试下,是否applicationContext.xml里面包含了多个配置文件的路径,然后ac包含了所有配置文件中的bean?
答案是是的。
<beans>
<import resource="classpath:applicationContext.xml" />
<import resource="classpath:applicationContext1.xml" />
</beans>
路径在src下,applicationContext和applicationContext1的bean都可以被访问。