Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

java - Spring MVC - should my domain classes implement Serializable for over-the-wire transfer?

I'm trying to learn Spring Boot by implementing a simple REST API.

My understanding was that if I need to transfer an object over the wire, that object should implement Serializable.

In many examples on the net though, including official ones, domain classes that need to be transferred from server to client (or vice-versa) do not to implement Serializable.

For instance: https://spring.io/guides/gs/rest-service/

But in some cases, they do:

For instance: https://github.com/szerhusenBC/jwt-spring-security-demo/blob/master/src/main/java/org/zerhusen/security/JwtAuthenticationRequest.java

Is there a general rule of thumb on when to implement Serializable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To update this, advice about Serializable has changed, the recommendation currently seems to be Don’t use Serializable for anything.

Using the Java serialization API means you need something in Java on the other side of the wire to deserialize the objects, so you have to control the code that deserializes as well as the code that serializes.

This typically isn't relevant for REST applications, consuming the application response is the business of someone else's code, usually outside your organization. When building a REST application it's normal to try to avoid imposing limitations on what is consuming it, picking a format that is more technology-agnostic and broadly available.

Some reasons for having an object implement java.io.Serializable would be:

  • so you can put it in an HttpSession

  • so you can pass it across a network between parts of a distributed application

  • so you can save it to the file system and restore it later (for instance, you could make the contents of a queue serializable and have the queue contents saved when the application shuts down, reading from the save location when the application starts to restore the queue to its state on shutdown).

In all these cases, you serialize so you can save something to a filesystem or send it across a network.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...