学习报告

  • 指 Spring 创建对象的过程中,将对象依赖属性(简单值,集合,对象)通过配置设值给该对象
  1. 在 Packge【pojo】下新建一个【JuiceMaker】类:
package pojo; public class JuiceMaker { // 唯一关联了一个 Source 对象 private Source source = null; /* setter and getter */ public String makeJuice(){ String juice = "xxx用户点了一杯" + source.getFruit() + source.getSugar() + source.getSize(); return juice; } }
  1. 在 xml 文件中配置 JuiceMaker 对象:
  • 注意:这里要使用 ref 来注入另一个对象
<?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 name="source" class="pojo.Source"> <property name="fruit" value="橙子"/> <property name="sugar" value="多糖"/> <property name="size" value="超大杯"/> </bean> <bean name="juickMaker" class="pojo.JuiceMaker"> <property name="source" ref="source" /> </bean> </beans>
  1. 在 【TestSpring】 中添加如下代码:
package test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import pojo.JuiceMaker; import pojo.Source; public class TestSpring { @Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext( new String[]{"applicationContext.xml"} ); Source source = (Source) context.getBean("source"); System.out.println(source.getFruit()); System.out.println(source.getSugar()); System.out.println(source.getSize()); JuiceMaker juiceMaker = (JuiceMaker) context.getBean("juickMaker"); System.out.println(juiceMaker.makeJuice()); } }
  1. 运行测试代码:

总结:IoC 和 DI 其实是同一个概念的不同角度描述,DI 相对 IoC 而言,明确描述了“被注入对象依赖 IoC 容器配置依赖对象”

IoC 如何实现的

最后我们简单说说IoC是如何实现的。想象一下如果我们自己来实现这个依赖注入的功能,我们怎么来做? 无外乎:

  1. 读取标注或者配置文件,看看JuiceMaker依赖的是哪个Source,拿到类名
  2. 使用反射的API,基于类名实例化对应的对象实例
  3. 将对象实例,通过构造函数或者 setter,传递给 JuiceMaker

我们发现其实自己来实现也不是很难,Spring实际也就是这么做的。这么看的话其实IoC就是一个工厂模式的升级版!当然要做一个成熟的IoC框架,还是非常多细致的工作要做,Spring不仅提供了一个已经成为业界标准的Java IoC框架,还提供了更多强大的功能,所以大家就别去造轮子啦!希望了解IoC更多实现细节不妨通过学习Spring的源码来加深理解!

posted @ 2021-09-11 19:58  禁小呆  阅读(37)  评论(0)    收藏  举报