【总结】Spring IOC加载方式配置文件方式

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都可以被访问。


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值