Naman Gala
Naman Gala

Reputation: 4692

Spring services should be serializable

I am developing Spring-mvc application.

I am getting NotSerializableException.

The exception is coming on the restart of the server. I search for the solution and got to know that session scoped beans should be serialized.

My session scoped bean implements serializable, but it gives exception for injected beans and services.

It asks me to serialize all injected beans and services.

I have serialized my beans but is it required to serialize services also.

Is it accepted behavior to serialize services also? If yes then will I have to serialize all the services in my applications?

Thanks.

Upvotes: 3

Views: 7927

Answers (2)

Joeblade
Joeblade

Reputation: 1743

As Mahendra already pointed out:

While deserializing the object, transient fields will reset to default value, so you might need to reinitialize it using if( transientField == null) { .. }

When you make a serializable bean, make sure that any reference you don't want to store to disk is marked as transient. This means that after the bean is loaded you re-set the members of the bean that were set as null.

for instance:

private transient SomeService localServiceRef;
SomeService getSomeService() {
    if (localServiceRef == null) {
        localServiceRef = SomeService.getInstance();
    }
    return localServiceRef;
}

Or you can store the id locally, and have a transient resolved object

private String objectId;
private transient SomeObject localObject;
SomeObject getLocalObject() {
    if (localObject == null) {
        localObject = SomeObjectFactory.getById(objectId);
    }
    return localObject;
}

Though this ofcourse depends on your actual code.

Personally I don't like working with beans that actually contain services and suchlike. I prefer having beans as value objects and services to be findable through other means.

Upvotes: 3

Mahendra
Mahendra

Reputation: 333

Tomcat does serialize session scope bean whenever you restart or shutdown it and restore the session while starting. You can implement serializable for beans which you want to be restored. otherwise skip this error.

Edit: Making a class serializable means that class must not contain non-serializable references or those references must be declared transient.

While deserializing the object, transient fields will reset to default value, so you might need to reinitialize it using if( transientField == null) { .. }

Upvotes: 5

Related Questions