ApplicationContext常用的三种实现类

Spring为ApplicationContext提供了很多实现类,其中有三个比较常用的:
ClassPathXmlApplicationContext,
FileSystemXmlApplicationContext,
XmlWebApplicationContext。

ClassPathXmlApplicationContext

从类路径下的XML文件中载入上下文定义信息:

ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
Hello hello = (Hello) act.getBean("hello");
hello.show();

其中applicationContext.xml文件如下:

  <bean id="hello" class="com.neusoft.services.HelloDaoImpl">
    <property name="pname" value=""></property>
  </bean>
  
  <bean id="persons" class="com.neusoft.services.person" init-method="init">
    <property name="pid" value="1001"></property>
    <property name="pname" value="哈哈"></property>
  </bean>

使用ClassPathXmlApplicationContext实现类读取xml文件时,只需要给出文件名,并将xml文件放到类路径下即可。

FileSystemXmlApplicationContext

从文件系统路径下的XML文件中载入上下文定义信息:

ApplicationContext act = new FileSystemXmlApplicationContext("D:/javaWorkSpace/spring2/src/applicationContext.xml");
person persons = (person) act.getBean("persons");
persons.show();

此时只填写XML文件的文件名会报错:

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: 
IOException parsing XML document from file 
[D:\javaWorkSpace\spring2\applicationContext.xml];
 nested exception is java.io.FileNotFoundException: 
 applicationContext.xml (系统找不到指定的文件。)

提示系统找不到指定的文件,因为FileSystemXmlApplicationContext实现类会从文件系统路径下读取xml文件,只写xml文件名找不到文件。但是,此处可以写成FileSystemXmlApplicationContext(“src/applicationContext.xml”),同样可以运行。

XmlWebApplicationContext

通过ContextLoaderListener从内部导入context文件。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值