peter tong wrote:Sorry but still has some unknown, if create a stateless object that doesn't change its internal state, then is this like create a class with all static member and static method? Why need create such Singleton, stateless object (bean) in spring?
No. The use of static fields is a completely different matter. In general, you must stay far far away from static fields altogether, regardless of whether you're trying to implement a stateless or a stateful type.
A stateless type doesn't evolve
over time. This doesn't mean it can't have any instance fields. It just means that those fields shouldn't change value after the object has been constructed, and any objects referenced by such fields should also be stateless. Once again, making a type immutable is a great way of ensuring an object is stateless.
Your services and controllers should be stateless. Here is an example:
This service is stateless because it only consists of a reference to a repository, and the reference never changes. The repository itself should also be stateless: it only consists of a reference to a data source.
An example of a class that is not stateless is the
ChessGame class used inside the
makeMove() method. The state of the game is changed when
applyMove() is called. This isn't a problem, because the
ChessGame is created by the repository at the start of the
makeMove() method and then discarded by the controller at the end of the request. Its lifetime is restricted to a small part of the current request, so it won't be accessed by multiple threads.
If the
ChessGame was stored in a field, rather than retrieved from a database, you'd be in trouble: the service that has a reference to the chess game is now stateful as well and can no longer be shared between requests safely.