虽然其他人已经正确地指出,在大多数情况下,DI 容器不会将依赖项注入到它们没有实例化的 bean 中,但这并不完全正确。
Spring 有一个很棒的特性,当你使用new A()
. 您只需要使用AspectJ 并使用annotation标记您的 bean@Configurable
。
@Configurable
public class A {
@Inject private B b;
}
它实际上是一个很棒的功能,因为您可以在仍然尊重您的 DI 的同时执行 Active Record 样式的 POJO(实际上 Spring Roo 就是这样做的)。
您还应该知道,使用 Spring,您可以在使用AutowireCapableBeanFactory实例化 bean 后以编程方式自动装配 bean 。这就是它通常自动装配 JUnit 测试用例类的方式,因为 JUnit 创建了测试用例类。
是的 Spring 不是 CDI,但理论上你可以为 CDI 编写自己的@Configurable
,或者可能有一种 CDI 方式来执行上述操作。
That being said the above is sort of a sophisticated feature (and kind of a hack) and as @JanGroth mentioned understaning the lifecycle bean management of the container is critical whether its CDI, Spring, Guice etc.