美文网首页我爱编程
Spring学习之Spring IoC 容器(Applicati

Spring学习之Spring IoC 容器(Applicati

作者: 北有花开 | 来源:发表于2018-05-23 20:59 被阅读13次

    在 org.springframework.context.ApplicationContext接口被定义。 spring 中较高级的容器。除了有BeanFactory 相同功能之外,还增加了企业所需要的功能。比如,从属性文件中解析文本信息和将事件传递给所指定的监听器。
    最常被使用的 ApplicationContext 接口实现:
    (1)、FileSystemXmlApplicationContext:该容器从 XML 文件中加载已被定义的 bean。在这里,你需要提供给构造器 XML 文件的完整路径。
    (2)、ClassPathXmlApplicationContext:该容器从 XML 文件中加载已被定义的 bean。在这里,你不需要提供 XML 文件的完整路径,只需正确配置 CLASSPATH 环境变量即可,因为,容器会从 CLASSPATH 中搜索 bean 配置文件。
    (3)、WebXmlApplicationContext:该容器会在一个 web 应用程序的范围内加载在 XML 文件中已被定义的 bean。
    这是在上一篇文章中介绍到的,一些知识点。下面来看看如何使用。

    FileSystemXmlApplicationContext使用

    第一步:在你的电脑中任何一个位置创建一个Beans.xml文件,我这儿在桌面上创建了一个。你也可以复制上篇文章中的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工程定制的。

    相关文章

      网友评论

        本文标题:Spring学习之Spring IoC 容器(Applicati

        本文链接:https://www.haomeiwen.com/subject/nsedjftx.html