Spring系列之(二)Spring基于XML的IOC实例

Spring基于XML的IOC实例

将改进后的工厂模式通过Spring来实现,解析配置文件、创建仓库,将对象存入仓库的过程都由Spring来做,我们只需要配置好配置文件,获取仓库中的对象即可

1. 在pom中引入Spring环境

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>day01_eesy_02spring</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.11.RELEASE</version>
        </dependency>
    </dependencies>

</project>

2. 业务层和持久层结构及代码

结构
在这里插入图片描述
业务层
在这里插入图片描述
持久层
在这里插入图片描述

3. 创建并配置配置文件

在这里插入图片描述
beans.xml中约束的获取
访问网址:Spring Framework 中文文档
在这里插入图片描述

4. 表现层测试

package com.itheima.ui;

import com.itheima.dao.IUserDao;
import com.itheima.service.IUserService;
import com.itheima.service.impl.IUserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {

    public static void main(String[] args) {
        //拿到容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        //从容器中获取指定的Bean,下面的两种方式均可
        IUserDao iUserDao =  (IUserDao) applicationContext.getBean("IUserDao");
        IUserService iUserService = applicationContext.getBean("IUserService", IUserService.class);

        System.out.println(iUserDao);
        System.out.println(iUserService);
    }
}

在这里插入图片描述

5. ApplicationContext的三个常用实现类

在上述的测试中,使用的是ClassPathXmlApplicationContext这个实现类,此处实际上是可以使用三个实现类的
在这里插入图片描述

  1. ClassPathXmlApplicationContext
    加载类路径下的配置文件
  2. FileSystemXmlApplicationContext
    加载磁盘任意路径下的配置文件(必须有访问权限)
  3. AnnotationConfigApplicationContext
    用于读取注解创建容器

6. ApplicationContext和BeanFactory两个接口

  1. ApplicationContext 单例对象适用,更常用
    构建核心容器时,创建对象采取的策略是立即加载的方式,只要一读取完配置文件马上就创建配置文件中的配置的对象。
  2. BeanFactory 多例对象适用
    构建核心容器时,创建对象采取的策略是延迟加载的方式,什么时候根据id获取对象,什么时候才真正的创建对象。
posted @   刘二水  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示