spring-core-2-14 | IoC主要实现策略:面试官总问IoC和DI的区别,他真的理解吗?

IoC 主要实现策略

维基百科(https://en.wikipedia.org/wiki/Inversion_of_control)

Implementation techniques 小节的定义:

“In object-oriented programming, there are several basic techniques to implement inversion of control. These are:
面向对象编程中, 有以下几种IoC的基础实现策略:

Using a service locator pattern

服务定位模式(Service Locator), 这种模式是 Java EE 里定义的, 通常通过 JNDI 这种技术来获取 Java EE 的组件, 比如 EJB组件, DataSource等

Using dependency injection, for example

依赖注入(DI), 比如下面的例子:
实际上不仅在SpringFramework, 在 EJB 3.0 之后也有相关的实现

Constructor injection

构造器注入

Parameter injection

参数注入

Setter injection

Setter注入

Interface injection

接口注入

Using a contextualized lookup

上下文中的依赖查询, 这是另一种技术实现了, 比如 Java Beans 里有一个通用的上下文, 叫做 beancontext, 里面既可以传输Bean, 也可以管理Bean的层次性. spring的很多实现都是来自于这方面的灵感.

Using template method design pattern

模板方法的设计模式, 比如spring里面的 jdbcTemplate, 里面提供了一个 callback的回调方式, 我们不需要关心 callBack 从哪里来, 只需要用, 这也是 控制反转 的一个体现.

Using strategy design pattern

策略模式, 不太好举例.

《Expert One-on-One™ J2EE™ Development without EJB™》提到的主要实现策略:

这是本书, 由spring的两名作者编写, 其思想会极大影响我们对spring的看法. 主要思想就是开发J2EE程序是否可以脱离EJB, 认为 EJB 是不重要的, 重要的是其中的思想.

来自“Chapter 6. Lightweight Containers and Inversion of Control

“IoC is a broad concept that can be implemented in different ways. There are two main types:
IoC可以有不同的实现方式, 其中有两种主要的策略:

Dependency Lookup:

The container provides callbacks to components, and a lookup context. This is the EJB and Apache Avalon approach. It leaves the onus on each component to use container APIs to look up resources and collaborators. The Inversion of Control is
limited to the container invoking callback methods that application code can use to obtain
resources.
依赖查询, 容器会提供一种回调机制到组件, 通过上下文查询的方式能够拿到这个组件.
EJB 和 Avalon 就是典型的框架, 现在都不太流行了.

Dependency Injection:

Components do no look up; they provide plain Java methods enabling the container to resolve dependencies. The container is wholly
responsible for wiring up components, passing resolved objects in to JavaBean properties or
constructors. Use of JavaBean properties is called Setter Injection; use of constructor arguments is called Constructor Injection.”
依赖注入, 组件不需要被查找, 通常由容器帮我们自动注入来做一些事情, 或者我们手动注入.
EJB 3.0其实也已经实现了, spring更不必说.

IoC和DI的区别

DI只是IoC的一种实现方式, 实际上我们也看到了, 实现策略多着呢.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值