如何在反序列化时重新附加单例Spring bean [英] how to reattach singleton Spring beans upon deserialization

查看:158
本文介绍了如何在反序列化时重新附加单例Spring bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在反序列化后将单例范围的依赖项重新注入原型Spring bean。

I want to reinject singleton-scoped dependencies into prototype Spring beans, after they have been deserialized.

假设我有一个Process bean,它取决于Repository bean。 Repository bean的作用域是单例,但Process bean是原型作用域。我会定期对序列进行序列化,然后对其进行反序列化。

Say I've got a Process bean, which depends on a Repository bean. The Repository bean is a scoped as a singleton, but the Process bean is prototype-scoped. Periodically I serialize the Process, and then later deserialize it.

class Process {
   private Repository repository;
   // getters, setters, etc.
}

我不知道想要序列化和反序列化存储库。我也不想将瞬态放在成员变量上,该成员变量在Process中包含对它的引用,也不是对某种代理的引用,或者除了声明为存储库的普通旧成员变量之外的其他任何内容。

I don't want to serialize and deserialize the Repository. Nor do I want to put "transient" on the member variable that holds a reference to it in Process, nor a reference to some kind of proxy, or anything other than a plain old member variable declared as a Repository.

我想我想要的是让Process的依赖关系填充一个可序列化的代理,该代理指向(通过瞬态引用)到Repository,并且在反序列化时,可以再次找到Repository 。我怎么能自定义Spring呢?

What I think I want is for the Process to have its dependency filled with a serializable proxy that points (with a transient reference) to the Repository, and, upon deserialization, can find the Repository again. How could I customize Spring to do that?

我想我可以使用代理来保存依赖引用,就像。我希望我可以使用那种确切的技术。但是我看到Spring生成的代理不是可序列化的,文档说如果我将它与单例bean一起使用,我会得到一个例外。

I figure I could use a proxy to hold the dependency references, much like . I wish I could use that exact technique. But the proxy I've seen Spring generate isn't serializable, and the docs say that if I use it with a singleton bean, I'll get an exception.

我可以在单例bean上使用自定义作用域,当要求自定义作用域bean时,它总是提供代理。这是一个好主意吗?其他想法?

I could use a custom scope, perhaps, on the singleton beans, that would always supply a proxy when asked for a custom-scoped bean. Is that a good idea? Other ideas?

推荐答案

在反序列化对象时添加使用方面添加注入步骤怎么样?

How about added using aspects to add an injection step when you deserialize the object?

你需要AspectJ或类似的东西。它与Spring中的@Configurable函数非常相似。

You would need AspectJ or similar for this. It would work very similarly to the @Configurable function in Spring.

例如。添加一些关于private void readObject(ObjectInputStream in)throws IOException,ClassNotFoundException方法的建议

e.g. add some advice around the a "private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException" method

本文也可以提供帮助: http://java.sun.com/developer/technicalArticles/Programming/serialization/

This article may also help: http://java.sun.com/developer/technicalArticles/Programming/serialization/

这篇关于如何在反序列化时重新附加单例Spring bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆