具有非托管对象的 CDI
假设我有两个类,第一个是没有任何属性、字段或注释的类:
public class B {}
还有一个被 B 注入的类,如下所示:
public class A {
@Inject
private B b;
public B getB() {
return b;
}
}
现在,类 A 在我们使用它之前毫无用处,因此有两个选项:
- @Inject it
- 构造使用值得信赖的“new A()”手动进行注入。
如果 A 被注入,CDI 会对其进行管理,并且会很好地注入具有 @Dependent 隐式作用域的 B。很酷,正是我想要的。
但是,如果我手动构造 A(假设在工厂或构建器中),CDI 完全忽略我的对象,并且不会注入 B 类型的对象。
示例我正在谈论它不起作用的情况,这里对象 a将始终保持为空:
public class Builder {
@Inject
private A a;
public static Builder ofTypeSomething() {
// do some magic here
return new Builder();
}
private Builder() {
// and some more here
}
}
为什么这不起作用?
A 类是一个有效的托管 bean,并且具有有效的作用域,就像 B 类一样。即使我将 @Producer 添加到静态方法中,它也不会改变任何内容(这很好,因为静态方法的思想是调用它,不要在任何地方注入 Builder)。
Suppose that I have two classes, first a class without any properties, fields or annotations:
public class B {}
And a class which gets B injected, like this:
public class A {
@Inject
private B b;
public B getB() {
return b;
}
}
Now class A is pretty useless until we use it, so there are two options:
- @Inject it
- Construct it manually, using the trusty "new A()"
If A gets injected, CDI manages it and is kind enough to inject B which has the implicit scope of @Dependent. Cool, just what I want.
However, if I manually construct A (let's say in a factory or a builder), CDI completely ignores my object and won't inject an object of type B.
Example I'm talking about when it doesn't work, here object a will always remain null:
public class Builder {
@Inject
private A a;
public static Builder ofTypeSomething() {
// do some magic here
return new Builder();
}
private Builder() {
// and some more here
}
}
Why doesn't this work?
Class A is a valid managed bean and has a valid scope, just like class B. Even if I add @Producer to the static method, it won't change anything (which is fine, cause the idea of the static method is to call it, not to inject Builder anywhere).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
依赖注入虽然有用,但并不神奇。 DI 的工作方式是,当您向容器请求对象的实例时,容器首先构造它(通过 new()),然后设置依赖项(如何发生取决于您的框架)。
如果您自己构造实体,那么容器不知道您已经构造了实体,并且无法设置实体的依赖关系。
如果您想使用工厂,那么大多数框架都有某种配置实体的方法,以便容器知道进行静态工厂方法调用而不是调用实体的构造函数。但是,您仍然必须从容器中获取实体。
编辑:此站点似乎演示了如何在 CDI 中使用工厂。
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.