David Parks
David Parks

Reputation: 32101

Spring: serializing objects with references to non-serializable beans

The class below (my implementation of UserDetailsService) gets tied to the session and the session gets serialized (in google apps engine).

I watched a Spring 3 presentation recently that said that beans, such as userDao, shown below, are loaded by a proxy which doesn't serialize the bean, but stores only the name and re-obtains the reference on deserialization.

But with the below code I'm getting a NotSerializableException: com.prepayproxy.dataaccesslayer.GAEUserDao

@Service("springUserDetailsService")
public class SpringUserDetailsService implements UserDetailsService, Serializable {
    @Resource(name="userDao")
    private IUserDao userDao;
    //...
}

Upvotes: 3

Views: 2356

Answers (1)

DwB
DwB

Reputation: 38318

You have 2 options:

  1. Mark the dao as transient so it does not serialize.
  2. Serialize the dao yourself.

Java provides a means to serialize non-serializable objects. You will need to implement


 private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;

The Serializable interface includes a writeup of these methods. Here is a link to the docs (java 1.6) Serializable

Upvotes: 2

Related Questions