Eric小屋

  • 入门案例代码实现
  • 首页
  • 学习笔记
    • JAVA
    • Spring
    • Node.js
    • Vue
  • 学习文档
  • 案例项目
  • 课程笔记
  • 问题解决
登录

DI 入门案例

  • Eric
  • 2024-03-08
  • 0

DI入门案例思路分析

1、基于IoC管理bean

2、Service中使用new形式创建的Dao对象是否保存

3、Service中需要的Dao对象如何进入到Service中

4、Service与Dao间的关系如何描述

入门案例代码实现

1、在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方法

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/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--bean标签标示配置bean
    	id属性标示给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>
  • name="bookDao"中bookDao的作用是让Spring的IOC容器在获取到名称后,将首字母大写,前面加set找对应的setBookDao()方法进行对象注入
  • ref="bookDao"中bookDao的作用是让Spring能在IOC容器中找到id为bookDao的Bean对象给bookService进行注入

4、运行程序

联系作者:2572976830@qq.com
© 2025 Eric小屋
Theme by Wing
京ICP备2023032157号 京公网安备11011402053616号
  • {{ item.name }}
  • {{ item.name }}