Spring
的
IOC
入门案例已经完成,但是在
BookServiceImpl
的类中依然存在
BookDaoImpl
对象的
new
操作,它们之间的耦合度还是比较高,这块该如何解决,就需要用到下面的
DI:
依赖注入
。
DI
入门案例
对于
DI
的入门案例,我们依然先
分析思路
然后再
代码实现
入门案例思路分析
(1)
要想实现依赖注入,必须要基于
IOC
管理
Bean
DI
的入门案例要依赖于前面
IOC
的入门案例
(2)Service
中使用
new
形式创建的
Dao
对象是否保留
?
需要删除掉,最终要使用
IOC
容器中的
bean
对象
(3)Service
中需要的
Dao
对象如何进入到
Service
中
?
在
Service
中提供方法,让
Spring
的
IOC
容器可以通过该方法传入
bean
对象
(4)Service
与
Dao
间的关系如何描述
?
使用配置文件
入门案例代码实现
需求 : 基于 IOC 入门案例,在 BookServiceImpl 类中删除 new 对象的方式,使用 Spring 的 DI 完成Dao 层的注入1. 删除业务层中使用 new 的方式创建的 dao 对象2. 在业务层提供 BookDao 的 setter 方法3. 在配置文件中添加依赖注入的配置4. 运行程序调用方法
步骤
1:
去除代码中的
new
在
BookServiceImpl
类中,删除业务层中使用
new
的方式创建的
dao
对象
public class BookServiceImpl implements BookService {// 删除业务层中使用 new 的方式创建的 dao 对象private BookDao bookDao ;public void save () {System . out . println ( "book service save ..." );bookDao . save ();}}
步骤
2:
为属性提供
setter
方法
在
BookServiceImpl
类中
,
为
BookDao
提供
setter
方法
public class BookServiceImpl implements BookService {// 删除业务层中使用 new 的方式创建的 dao 对象private BookDao bookDao ;public void save () {System . out . println ( "book service save ..." );bookDao . save ();}// 提供对应的 set 方法public void setBookDao ( BookDao bookDao ) {this . bookDao = bookDao ;}}
步骤
3:
修改配置完成注入
在配置文件中添加依赖注入的配置
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd" ><!--bean 标签标示配置 beanid属性标示给 bean 起名字class属性表示给 bean 定义类型--><bean id = "bookDao" class = "com.itheima.dao.impl.BookDaoImpl" /><bean id = "bookService" class = "com.itheima.service.impl.BookServiceImpl" ><!--配置 server 与 dao 的关系 --><!--property标签表示配置当前 bean 的属性name属性表示配置哪一个具体的属性ref属性表示参照哪一个 bean--><property name = "bookDao" ref = "bookDao" /></bean></beans>
注意
:
配置中的两个
bookDao
的含义是不一样的
name="bookDao"
中
bookDao
的作用是让
Spring
的
IOC
容器在获取到名称后,将首字母大写,前
面加
set
找对应的
setBookDao()
方法进行对象注入
ref="bookDao"
中
bookDao
的作用是让
Spring
能在
IOC
容器中找到
id
为
bookDao
的
Bean
对象给
bookService
进行注入
综上所述,对应关系如下
:
![](https://i-blog.csdnimg.cn/blog_migrate/0cb2c4daed39e7838e9dc98a2f3f002b.png)
步骤
4:
运行程序
运行,测试结果为:
![](https://i-blog.csdnimg.cn/blog_migrate/f8439a799ec0f26aee2c8fce8de702b0.png)