其他分享
首页 > 其他分享> > 重新认识IoC

重新认识IoC

作者:互联网

1. IoC发展简介

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

维基百科(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:

3. IoC容器的职责:IoC除了依赖注入,还涵盖哪些职责呢?

维基百科(https://en.wikipedia.org/wiki/lnversion_of_control)
在Overview小节中提到:

Inversion of control serves the following design purposes:

Inversion of control is sometimes facetiously referred to as the 'Hollywood Principle: Don’t call us, well call you¹>.

通用职责

4. IoC容器的实现

主要实现

5. 传统IoC容器实现

Java Beans作为IoC容器

6. 轻量级IoC容器:如何界定IoC容器的“轻重”?

7. 依赖查找 VS. 依赖注入

类型依赖注入实现便利性代码侵入性API依赖性可读性
依赖查找主动获取相对繁琐侵入业务逻辑依赖容器API良好
依赖注入被动提供相对便利低侵入性不依赖容器API一般

8. 构造器注入 VS. Setter 注入

“The Spring team generally advocates constructor injection, as it lets you implement application components as immutable objects and ensures that required dependencies are not null. Furthermore, constructor-injected components are always returned to the client (calling) code in a fully initialized state. As a side note, a large number of constructor arguments is a bad code smell, implying that the class likely has too many responsibilities and should be refactored to better address proper separation of concerns.

Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later. Management through JMX MBeans is therefore a compelling use case for setter inject ion.”

Disadvantages include:
The order in which setters are called is not expressed in any contract. Thus, we sometimes need to invoke a method after the last setter has been called to initialize the component. Spring provides the
org.springframework.beans.factory.InitializingBean interface for this; it also provides the ability to invoke an arbitrary init method. However, this contract must be documented to ensure correct use outside a container.

Not all the necessary setters may have been called before use. The object can thus be left partially configuredy

9. 面试题精选

答:简单地说,IoC是反转控制,类似于好莱坞原则,主要有依赖查找和依赖注入实现。

按照IoC的定义,很多东西都是IoC,JavaBeans是IoC的一个容器实现,Servlet容器也是IoC的实现,因为Servlet可以去依赖或反向通过JNDI的方式得到外部的一些资源包括DataSource或相关EJB组件,像Spring Framework或Peak Container的依赖注入框架也可以帮助实现我们的IoC。

如再扩展到反转控制,消息也算。

答:依赖查找是主动或手动的依赖查找方式,通常需要依赖容器或标准API实现。而依赖注入则是手动或自动依赖绑定的方式,无需依赖特定的容器和API。

答:

标签:重新认识,依赖,container,容器,EJB,Java,IoC
来源: https://blog.csdn.net/qq_36348557/article/details/120931934