烂笔头

扬帆起航,再出发!!!

0%

使用Spring IOC削减耦合

Spring源码下载地址

Spring中基于XML的IOC环境搭建

  1. pom.xml中引入Spring依赖
    1
    2
    3
    4
    5
    6
    7
    8
    <dependencies>
    <!--Spring依赖-->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.2.RELEASE</version>
    </dependency>
    </dependencies>

2.在resources目录下创建配置文件bean.xml(名称可改变)
3.导入约束 在Spring源码中的 spring-framework-5.0.2.RELEASE/docs/spring-framework-reference/index.html中点击core,然后搜索xmlns,将搜到的约束拷贝。

1
2
3
4
5
<?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">

4、将对象的创建交给Spring管理,在bean.xml中添加如下<bean>标签

1
2
3
<bean id="accountService" class="io.github.lonelyMrZhang.service.impl.AccountServiceImpl"></bean>

<bean id="accountDao" class="io.github.lonelyMrZhang.dao.impl.AccountDaoImpl"></bean>

5、获取Spring的IOC核心容器,并根据id获取对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package io.github.lonelyMrZhang.ui;

import io.github.lonelyMrZhang.dao.IAccountDao;
//import io.github.lonelyMrZhang.factory.BeanFactory;
import io.github.lonelyMrZhang.service.IAccountService;
import io.github.lonelyMrZhang.service.impl.AccountServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* @description: 模拟表现层,调用业务层
* @author: lonely.mr.zhang
* @date: 2020/6/12 12:53 上午
*/
public class Client {

/**
* 获取Spring的IOC核心容器,并根据id获取对象
* @param args
*/
public static void main(String[] args) {
//1、获取核心容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2、根据id获取对象
IAccountService accountService = (IAccountService)ac.getBean("accountService");
IAccountDao accountDao = ac.getBean("accountDao", IAccountDao.class);

System.out.println(accountService);
System.out.println(accountService);
}
}

ApplicationContext 三个常用实现类之间的区别

IDEA中光标停留在要查看的类上 按下ctrl + h便可查看该类的所有实现类:

ApplicationContext实现类

  • ClassPathXmlApplicationContext:可以加载类路径下的配置文件,要求配置文件必须在类路径下,不在类路径下加载不了。比较常用。
  • FileSystemXmlApplicationContext:可以加载磁盘任意路径下的有权限的配置文件
  • AnnotationConfigApplicationContext:读取注解创建文件。

IOC容器构建的两种方式

  • 懒汉模式
    通过BeanFactory构建Spring容器时,采用延迟加载的策略创建对象,即:什么时候根据id获取对象,什么时候真正的创建对象。适用多例模式

  • 饿汉模式
    通过ApplicationContext构建Spring核心容器时,采用立即加载的策略创建对象,即:只要一读取完配置文件马上就要创建配置文件中配置的对象。适用单例模式

项目GitHub地址

您的支持就是我更新的动力!有钱的捧个钱场,没钱的捧个人场,谢谢大家!