用于EJB和CDI bean的序列化的最佳实践 [英] Best practice for serialization for EJB and CDI beans
问题描述
EntityManager
和几个CDI bean。 我没有找到任何正确处理序列化的最佳做法。
- 将由
@Inject
和@PersistenceContext
注入的字段将重新注入反序列化? - 应该将其标记为
transient
? - 或者我应该忽略/关闭代码检查?
- 我是否真的为PMD提供访问所有这些领域的访问者? >
我知道这是一个老问题,但我相信提供的唯一答案是不正确的。
将由@Inject和@PersistenceContext注入的字段为
重新注入反序列化?
不,他们不会。我在一个集群环境中亲自体验了JBoss。如果bean具有钝化功能,则容器必须注入可序列化的代理。该代理被序列化和反序列化。一旦反序列化,它将定位适当的注射并重新连接。但是,如果您标记字段transient,则代理不会被序列化,当注入的资源被访问时,您将看到NPE。
应注意注入的资源或bean不必是可序列化的,因为代理将是。唯一的例外是@Dependent作用域bean,它们必须是可序列化的或注入瞬态的。这是因为在这种情况下不使用代理。
应该将其标记为短暂的?
否,见上文。
或者我应该忽略/关闭代码检查?
这取决于你,但这是我会做的。
我是否真的为PMD提供所有这些字段的访问者?
我不会。
在我们的项目中,当我们知道我们使用CDI时,我们禁用此检查。
I have not yet experienced any serialization-related issues. But PMD and Findbugs detect a bunch of potential problems regarding seriazation. A typical case is an injected logger that is being detected as non-serializable. but there are many more - EntityManager
and several CDI beans.
I have not found any best practices on how to deal with serialization correctly.
- will the fields, injected by
@Inject
and@PersistenceContext
be reinjected on deserialization? - should they be marked as
transient
? - or should I just ignore/switch off the code checks?
- should I really provide accessors to all those fields as PMD advises?
I realize this is an old question, but I believe the only answer provided is incorrect.
will the fields, injected by @Inject and @PersistenceContext be reinjected on deserialization?
No, they will not. I personally experienced this with JBoss in a clustered environment. If the bean is passivation capable, then the container must inject a serializable proxy. That proxy gets serialized and deserialized. Once deserialized, it will locate the proper injection and rewire it. However, if you mark the field transient, the proxy is not serialized and you will see NPEs when the injected resource is accessed.
It should be noted that the injected resource or bean does not have to be Serializable, because the proxy will be. The only exception is for @Dependent scoped beans which have to be serializable or the injection transient. This is because a proxy is not used in this case.
should they be marked as transient?
No, see above.
or should I just ignore/switch off the code checks?
This is up to you, but it is what I would do.
should I really provide accessors to all those fields as PMD advises?
No, I would not. In our projects, we disable this check when we know we are using CDI.
这篇关于用于EJB和CDI bean的序列化的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!