Spring學習之Spring IoC 容器(ApplicationContext容器)(5)

在 org.springframework.context.ApplicationContext接口被定義。 spring 中較高級的容器。除了有BeanFactory 相同功能之外,還增加了企業(yè)所需要的功能。比如,從屬性文件中解析文本信息和將事件傳遞給所指定的監(jiān)聽器。
最常被使用的 ApplicationContext 接口實現(xiàn):
(1)、FileSystemXmlApplicationContext:該容器從 XML 文件中加載已被定義的 bean。在這里,你需要提供給構造器 XML 文件的完整路徑。
(2)、ClassPathXmlApplicationContext:該容器從 XML 文件中加載已被定義的 bean。在這里,你不需要提供 XML 文件的完整路徑,只需正確配置 CLASSPATH 環(huán)境變量即可,因為,容器會從 CLASSPATH 中搜索 bean 配置文件。
(3)、WebXmlApplicationContext:該容器會在一個 web 應用程序的范圍內加載在 XML 文件中已被定義的 bean。
這是在上一篇文章中介紹到的,一些知識點。下面來看看如何使用。

FileSystemXmlApplicationContext使用

第一步:在你的電腦中任何一個位置創(chuàng)建一個Beans.xml文件,我這兒在桌面上創(chuàng)建了一個。你也可以復制上篇文章中的Beans.xml到桌面上。
第二步:修改Main.java中的代碼,如下:

     ApplicationContext context =
                new FileSystemXmlApplicationContext("C:\\Users\\Hunter\\Desktop\\Beans.xml");
        Students students = (Students) context.getBean("students");
        students.selfIntroduction();

第三步:運行程序得到上一篇一樣的結果。

ClassPathXmlApplicationContext使用

第一步:修改resources下的Beans.xml(其實可以不修改,只是為了看到不同的效果)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="students" class="com.hunter.bean.Students">
        <property name="name" value="小張"/>
        <property name="school" value="北大"/>
    </bean>

</beans>

我將姓名和學校都進行了修改。其他沒有變。
第二步:修改Main.java文件,代碼如下:

        ApplicationContext context =
                new ClassPathXmlApplicationContext("Beans.xml");
        Students students = (Students) context.getBean("students");
        students.selfIntroduction();

第三步:運行程序結果如下:


QQ截圖20180523205547.png

至于WebXmlApplicationContext這兒暫時不做介紹,因為它專為Web工程定制的。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容