rahul
rahul

Reputation: 33

Stateful and stateless beans in Spring

What do stateful and stateless beans in Spring mean? I googled it a lot but couldn't find a satisfactory answer.

Any help would be appreciated.

Upvotes: 1

Views: 10439

Answers (2)

ACV
ACV

Reputation: 10561

Spring allows for Singleton and Prototype bean scopes (plus request, session and global session for HTTP context).

Singleton means - there will only be 1 instance created of that class for the whole application context, or basically for the whole lifetime of an application (unless you have multiple contexts)

Every time a bean of that Singleton scoped class is requested by either getBean or is injected during runtime, it will be the same instance.

Prototype means - everytime a bean is requested by getBean or is injected, a new instance will be created. You should use this scope for beans which are stateful (have data saved in their instance variables).

Upvotes: 1

luboskrnac
luboskrnac

Reputation: 24561

State is most commonly represented by field variable that is not autowired.

So this is stateful bean:

@Component
public class Stateful {
    private int someCounter;

    ...
}

Stateless is bean one that doesn't have any class level variables or only autowired singleton bean instances to Stateless types.

Basically everything that can change the value within that bean and it's dependency tree (except local variables in methods) is state and should be avoided as much as possible.

So my example is thread-unsafe antipattern, because such defined bean is singleton. And singleton bean must be stateless.

Upvotes: 3

Related Questions