一篇文章带你掌握主流基础框架——Spring( 二 )


  • 使用对象时 , 由主动new创建对象转换为由外部提供对象
  • 此过程中对象创建控制权由程序转移到外部 , 被称为控制反转
DI(Dependency Injection)依赖注入:
  • 在容器中建立Bean与Bean之间的依赖关系和整个过程 , 被称为依赖注入
Spring技术对Ioc思想进行了实现:
  • Spring提供了一个容器 , 被称为Ioc容器 , 用来充当IoC思想的外部
  • IoC容器负责对象的创建 , 初始化等一系列工作 , 被创建和管理的对象在IoC容器中被称为Bean
// 数据层实现public class BookDaoImpl implements BookDao {public void save() {System.out.println("book dao save ...");}}// IoC容器/*包含daoservice两者可以建立连接*/// 业务层实现public class BookServiceImpl implements BookService {private BookDao bookDao;public void save() {bookDao.save();}}目的:充分解耦
  • IoC:使用IoC容器管理bean
  • DI:在IoC容器内将有依赖关系的bean进行关系绑定
最终效果:
  • 使用对象不仅可以直接从IoC容器中获取 , 还可以将已获得的Bean之间绑定依赖关系
IoC入门首先我们需要明白IoC的使用规则:
  1. IoC负责管理什么:Service和Dao
  2. 如何被管理的对象告知IoC容器:(配置)
  3. 被管理的对象交给IoC容器 , 如何获得IoC容器:(接口)
  4. IoC容器得到之后 , 如何获得Bean:(接口方法)
  5. 使用Spring所需要导入的坐标:(pom.xml)
下面我们给出IoC入门的详细步骤:
  1. 创建Maven项目 , 在pom.xml中导入坐标
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.10.RELEASE</version></dependency></dependencies>
  1. 创建Spring.xml的配置包(applicationContext.xml,导入坐标后xml中更新该XML)
<?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"><!--2.配置bean--><!--bean标签标示配置beanid属性标示给bean起名字class属性表示给bean定义类型(注意需要是实现类)--><bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl"/><bean id="bookService" class="com.itheima.service.impl.BookServiceImpl"/></beans>
  1. 主函数
package com.itheima;import com.itheima.dao.BookDao;import com.itheima.service.BookService;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class App2 {public static void main(String[] args) {//3.获取IoC容器ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");//4.获取bean(根据bean配置id获取)//BookDao bookDao = (BookDao) ctx.getBean("bookDao");//bookDao.save();// 注意:需要类型转化BookService bookService = (BookService) ctx.getBean("bookService");bookService.save();}}DI入门首先我们需要明白DI的使用规则:
  1. 基于IoC管理bean
  2. Service中使用new形式创建Dao对象是否保留:(否)
  3. Service中需要Dao对象如何进入到Service中:(提供方法)
  4. Service与Dao之间的关系如何描述:(配置)
下面我们给出DI入门的详细步骤(基于IoC入门):
  1. 删除new方法
public class BookServiceImpl implements BookService {//5.删除业务层中使用new的方式创建的dao对象private BookDao bookDao;public void save() {System.out.println("book service save ...");bookDao.save();}}

经验总结扩展阅读