user2049200
user2049200

Reputation: 127

How to avoid the serialization exception (NotSerializableException) with Spring Data

I have a problem with Spring Data, I receive some exception of NotSerializableException type.

Below an example to explain how I have this problem :

@Component
@Scope("session")
public class Bean implements Serializable {

   @Autowired
   private  FooRepository repository;

}

public interface FooRepository extends JpaRepository<Foo, Long>

After I look into in the code, I have seen that the interface org.springframework.data.repository.Reposotiry is not serializable.

And the last version of Spring Data hasn't changed.

I could override the serilization but I don't know if it's the best solution.

Could you tell me if you have found an other solution for this problem or workaroud.

Thank in advance.

Upvotes: 2

Views: 985

Answers (1)

user4695271
user4695271

Reputation:

You will "get the exception" when an instance must implement Serializable. The exception is thrown by either the serialization run-time or by the instance of the class.

I think the simplest fix is to make FooRepository "serializable", but eventually you cannot since it's a third-party library. So, in your case you must "mark" it as transient; once you do that it will be ignored by the serializable run-time.

@Component
@Scope("session")
public class Bean implements Serializable {

   @Autowired
   private transient FooRepository repository;

}

NOTE: That's in theory, I've never done that with an injected bean, but the result should be the same. Anyway, that applies to your issue, maybe not to your specific solution.

Upvotes: 1

Related Questions