IoC 入门案例(XML)

IoC 概念:2. IoC 控制反转

一、导入 Spring 坐标

pom.xml

1
2
3
4
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.13.RELEASE</version>
</dependency>

二、定义 Spring 管理的类(接口)

Service 接口

1
2
3
public interface BookService {
public void save();
}

Service 实现

1
2
3
4
5
6
public class BookServiceImpl implements BookService {
private BookDao bookDao = new BookDaoImpl();
public void save() {
bookDao.save();
}
}

三、创建 Spring 配置文件

*resources/applicationContext.xml

  • bean 标签表示配置一个 bean
  • id 属性表示给 bean 名字
  • class 属性表示给 bean 定义类型

bean 定义时 id 属性在同一个上下文中不能重复

1
2
3
4
5
6
7
8
9
<?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 -->
<bean id="bookDao" class="cn.pangcy.dao.impl.BookDaoImpl" />
<bean id="bookService" class="cn.pangcy.service.impl.BookServiceImpl" />
</beans>

四、初始化 IoC 容器

App 启动类

  • 通过 new ClassPathXmlApplicationContext 获取容器对象
  • 通过 ctx.getBean(“bean Id”) 获取对象

通过 getBean 获取的返回值是 Object 对象,需要强制转一下类型

1
2
3
4
5
6
7
8
9
10
public class App {
public static void main(String[] args) {
// 加载配置文件获取上下文对象,也就是容器对象
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

// 获取资源
BookService bookServcice = (BookService) ctx.getBean("bookService");
bookService.save();
}
}

IoC 入门案例(XML)
https://blog.pangcy.cn/2023/04/02/后端编程相关/java/spring/IoC 入门案例(XML)/
作者
子洋
发布于
2023年4月2日
许可协议