CDI with unmanaged objects

前端 未结 1 1771
醉梦人生
醉梦人生 2021-02-09 07:37

Suppose that I have two classes, first a class without any properties, fields or annotations:

public class B {}

And a class which gets B inject

相关标签:
1条回答
  • 2021-02-09 08:03

    Dependency injection, while useful, is not magical. The way DI works is that when you ask the container for an instance of an object the container first constructs it (via new()) and then sets the dependencies (how this happens depends on your framework).

    If you construct the entity yourself then the container has no idea you've constructed the entity and can't set the dependencies of the entity.

    If you want to use a factory then most frameworks have some way of configuring the entity so that the container knows to make a static factory method call and not call the constructor of the entity. However, you still have to obtain your entity from the container.

    Edit: This site seems to demonstrate how to use a factory in CDI.

    0 讨论(0)
提交回复
热议问题