Spring入门 基于XML的IoC环境搭建和入门 ApplicationContext的三个实现类 BeanFactory和ApplicationContext的区别

一、Spring基于XML的IoC环境搭建和入门

首先在pom.xml配置spring

<packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>

官网上可以查到,下面是代码
配置bean

<?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="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

示例

    <!-- id过去时的唯一标志,class反射要创建的全限定类名-->
    <bean id="accountService" class="com.bruce.service.impl.AccountServiceImpl"></bean>

二、获取核心容器ApplicationContext的三个实现类

在这里插入图片描述
*获取spring的IoC核心容器,并根据id获取对象
* ApplicationContextd的三个常用实现类:
* ClassPathXmlApplicationContext:它可以加载类路径下的配置文件,要求配置文件必须在类路径下。不在就运行不了。(和第二个比较这个更常用
* FileSystemXmlApplicationContext:它可以加载磁盘任意路径下的配置文件(必须有访问权限)
* AnnotationConfigApplicationContext:它用于读取注解创建容器的。(后面单独讲

使用ClassPathXmlApplicationContext
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
使用FileSystemXmlApplicationContext
ApplicationContext ac = new FileSystemXmlApplicationContext("D:\\ruanjiankaifa\\day01_03spring\\src\\main\\resources\\bean.xml");

BeanFactory和ApplicationContext的区别

* 核心容器的两个接口引发出的问题:
*      ApplicationContext:         单例对象适用
*          它在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说,只要一读取配置文件马上就创建配置文件中的对象。
*      BeanFactory:               多例对象适用
*          它在构建核心容器时,创建对象采取的策略是延迟加载的方式。也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象

我们可以在实现类写构造函数并输出对象创建成功,打断点的形式来进行演示这一过程。

    public AccountServiceImpl(){
    
    
        System.out.println("对象创建成功");
    }

ApplicationContext过程演示

此时刚到这一行,还没有走这一行的内容
在这里插入图片描述
执行下一步,表示读取完配置文件了。构造函数执行,创建了配置文件中的对象
在这里插入图片描述

BeanFactory过程演示

用的是过时的一个实现XmlBeanFactory
打断点执行,此时没有运行这一行
在这里插入图片描述
读取完配置文件后,仍然没有创建对象
在这里插入图片描述
在往下已经构建完工厂了,但是仍然没有创建对象
在这里插入图片描述
只有当真正用的时候才会创建对象
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42727032/article/details/104333461