The life cycle of a message-driven bean has two states, namely the ‘does not exist’ and ‘pooled’ state. A message-driven bean does not maintain any client specific state. It does not have the home and component interfaces. The following image shows the life cycle of a message-driven bean:
The container is responsible for maintaining the life cycle of a message-driven bean. A bean moves from the ‘does not exist’ to the ‘method ready’ state using the following methods:
- The container creates a bean instance by calling the newInstance() method on a class.
- The container assigns a context to the bean by invoking the setMessageDrivenContext() method.
- The container calls the ejbCreate() method. The initialization code should be written in this method.
The bean instance in the pooled state can perform operations using the onMessage() method. The container ensures that only one thread executes at a particular moment. The message -driven beans connect to the JMS server, consume messages from the server, and process those messages.
The bean instance can be removed by the container by calling the ejbRemove() method. By calling this method, the container moves the bean instance back to the ‘does not exist’ state.