Java 中的资源注入和依赖注入 (CDI) 有什么区别?

What is difference between resource injection and dependency injection (CDI) in Java?

学习JavaEE有一段时间了,发现JavaEE提供了两种注入机制

  1. 资源注入
  2. 依赖注入

请指导我了解资源注入和依赖注入之间的区别。

来自source

Resource injection enables you to inject any resource available in the JNDI namespace into any container-managed object, such as a servlet, an enterprise bean, or a managed bean. For eg, we can use resource injection to inject data sources, connectors, or any other desired resources available in the JNDI namespace.

Dependency injection enables us to turn regular Java classes into managed objects and to inject them into any other managed object (objects wich are managed by the container).

Difference between Resource Injection and Dependency Injection The differences between the RI and DI are listed below.

  1. Resource Injection can inject JNDI Resources directly whereas Dependency Injection cannot.

  2. Dependency Injection can inject Regular Classes (managed bean) directly whereas Resource Injection cannot.

  3. Resource Injection resolves by resource name whereas Dependency Injectin resolves by type.

  4. Dependency Injection is typesafe whereas Resoiurce Injection is not.

Java EE 提供了注入机制,使我们的对象能够获取对资源和其他依赖项的引用,而无需直接实例化它们(显式地使用“new”关键字)。我们只需在我们的 类 中声明所需的资源和其他依赖项,方法是绘制带有注释的字段或方法,这些注释表示编译器的注入点。

容器然后在运行时提供所需的实例。 Injection 的优点是它简化了我们的代码并将其与其依赖项的实现解耦。

这两种方法都有助于实现控制反转。

Take a look at one of my article I wrote on this.

Rahul Tripathi 的回答准确无误。但为了更简洁的方式来帮助您决定使用哪个,让我们这样看:DI 通常用于将实现 类 分配给接口。而 RI 用于从 JNDI 中提取 属性 值和 JDBC 连接。 DI 允许您针对接口编写代码并稍后决定使用哪个实现。有一些重叠,通常是当 RI 的对象不仅仅是一个 属性 值时,以及当 DI 用于传递 属性 值时。正如我已经提到的,这种重叠的一个很好的例子是 JDBC 连接。 JDBC 连接不仅是一个连接字符串(属性 值),它还是一个实现(要使用哪些驱动程序)。

我认为如果您正在使用 DI 并且需要传递一些 属性 值,请继续使用 DI。如果您正在使用 RI 并且需要传递一个对象,那么如果可能的话,不要只在 RI 中进行。最后,如果您同时使用两者,那么需要填写的文件就更多了。XML。

看看这个:Java EE Injection

Main differences between resource injection and DI: