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文件。