CDI 构造函数注入不适用于瞬态不可序列化依赖项
我非常喜欢 CDI 的构造函数注入,但现在我发现了一个用例,其中构造函数注入显然无法按预期工作。
在我的示例中,我有两个课程。类“BeanA”没有定义明确的范围,并且不实现 Serialized。类“BeanB”用@SessionScoped注释并且实现了Serialized。
public class BeanA{
}
@SessionScoped
public class BeanB implements Serializable{
@Inject
private BeanA beanA;
}
当我尝试将 BeanA 的实例注入到 BeanB 中时,我从 Weld 收到 UnserializedDependencyException,因为 BeanA 不可序列化。这是预期的行为。
当我用“transient”标记字段“beanA”时,注入工作没有问题:
@Inject
private transient BeanA beanA;
现在 Weld 不会抛出任何异常。
这对我来说非常好,但是当我想通过构造函数注入来实现这一点时,我的理解问题就出现了。当我执行以下操作时,它不再起作用:
@SessionScoped
public class BeanB implements Serializable{
private transient BeanA beanA;
@Inject
public BeanB(BeanA beanA){
this.beanA = beanA;
}
public BeanB(){}
}
使用此代码,我再次收到 UnserializedDependencyException。我认为构造函数注入和字段注入或多或少是等效的,但显然它们不是。我的错误是什么?
I like the constructor injection of CDI a lot but now I found a usecase where constructor injection apparently doesn't work as expected.
In my example I have two classes. Class "BeanA" has no explicit scope defined and does not implement Serializable. Class "BeanB" is annotated with @SessionScoped and does implement Serializable.
public class BeanA{
}
@SessionScoped
public class BeanB implements Serializable{
@Inject
private BeanA beanA;
}
When I try to inject an instance of BeanA into BeanB of cource I get an UnserializableDependencyException from Weld because BeanA isn't serializable. This is the expected behaviour.
When I mark the field "beanA" with "transient" the injection works without problems:
@Inject
private transient BeanA beanA;
Now Weld doesn't throw any exceptions.
This is perfectly fine for me but my understanding problem comes when I like to get this working with constructor injection. When I do the following it doesn't work anymore:
@SessionScoped
public class BeanB implements Serializable{
private transient BeanA beanA;
@Inject
public BeanB(BeanA beanA){
this.beanA = beanA;
}
public BeanB(){}
}
With this code I get the UnserializableDependencyException again. I thought that constructor injection and field injection are more or less equivalent but obviously they aren't. What is my mistake?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这似乎是一个错误。如果使 BeanA 可序列化,一切都会正常吗?另外您使用的是哪个版本的 Weld?
That seems like a bug. Does everything work well if you make BeanA serializable? Also which version of Weld are you using?