Announcement Announcement Module
Collapse
No announcement yet.
Good pattern for Serializable with reference to Spring bean? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Good pattern for Serializable with reference to Spring bean?

    Does anyone have any suggestions about a good pattern for deserializing beans that have injected services from a Spring container?

    I have see a couple of relevant posts (http://forum.springframework.org/showthread.php?t=18753, and http://forum.springframework.org/showthread.php?t=17887, http://forum.springframework.org/arc.../t-10129.html), but no really solid discussion of this topic.

  • #2
    Some ideas begged and borrowed from various places...

    public class Foo implements Serializable {

    private transient Service service;
    private String name;

    // ... getters and setters for name ...

    public void setService(Service service) {
    this.service = service;
    }
    }

    We have a bean class Foo implements Serializable (hopefully), and it requires a service to be injected before it is in a valid state. It might be a prototype bean (e.g. some of the examples in the original post), or it might not be. In my example it is just some poor bean created on the fly and enhanced by some other Spring-aware factory. It gets serialized. Fine, we have marked the service as transient as above, so no problems so far. Now it gets deserialized and we have a problem: the deserialization takes place deep in the VM, with no easy way to use the factory that initially created the object.

    There is a bit of a chicken-and-egg situation here, and it really seems to me that we have to lose IoC somewhere to make things work satisfactorily.

    The only way I can see to do it is to provide a traditional (non-Spring) singleton and make sure it knows about the Spring ApplicationContext, e.g.

    public class Foo implements Serializable {

    // ... same stuff as before ...

    private Object readResolve throws ObjectStreamException {

    // Singleton static accessor to grab the factory
    FooFactory factory = FooFactory.getInstance();

    // Non-static factory method for Foo objects, so that it can be
    // injected with services etc. by IoC.
    Foo foo = factory.getInstance();
    foo.setName(this.name);

    return foo;
    }

    The issue is that FooFactory has to have that static singleton accesssor, and yet it has to return a Spring bean. Is this a nasty hack, or can someone see a refinement?

    One other thing: the pattern above also helps solve one of the other problem threads: to deserialize to a prototype Spring bean, which might be necessary if we want to add AOP to our Foo. It wouldn't be very difficult for the FooFactory to pull the Foo from the BeanFactory instead of using an explicit constructor (the implementation of the factory is not specified above anyway).

    Comment

    Working...
    X