Explain the life cycle of Stateful Session Bean.
There are three states in the life cycle of a stateful session bean:
- Does not exist
- Method ready
Initially the bean is in does not exist state. The client initiates the life cycle of the stateful session bean by obtaining the reference of the bean. The container creates an instance of the bean and performs dependency injection, if any. After this, the container invokes the method annotated with @PostConstruct annotation if present in the bean. The bean is now in the method ready state to have its business methods invoked by the client.
During its life time in the method ready state, the container may passivate the bean by moving it from memory to secondary storage. The bean is said to be in passive state. The container invokes the method annotated with @PrePassivate, if any, immediately before passivation. If a client invokes a business method on the bean while it is in the passive stage, the container activates the bean, calls the method annotated with @PostActivate, if any, and then moves it to the ready stage.
At the end of the lifecycle, the client invokes a method annotated @Remove (which is optional), and the container calls the method annotated @PreDestroy, if any. The bean’s instance is then ready for garbage collection. The life cycle of stateful session bean can be understood with the following diagram.