Stateful session beans support callback events for the following events:
A method in the bean may be annotated to be executed when any of these events occur.
The PostContruct callback happens immediately after a bean is instantiated in the EJB container.
The bean may use dependency injection to get reference to other beans or resources, in that case the event happens after these injections are completed.
The method itself doesn’t have to have a certain name. It can be called anything and is a good place to for example create a Logger instance for logging.
A method could look like this:
A stateful session bean can store information between client calls, as opposed to stateless session beans that cannot remember anything about the user from its last call.
A stateful session bean looks like an ordinary Java class except that it is annotated with the @Stateful annotation.
The typical stateful session bean is a shopping cart which keeps track of items that the user has added duing it’s visit to a particular site.
Below is an example of how a shopping cart stateful session bean could be declared:
It is possible to invoke a Session Bean over the network by declaring the interface of a session bean as Remote. This is done using the @Remote annotation, which is equal to having it extend the java.rmi.Remote interface.
The reference to the bean that gets aquired by a client is not a local reference on the same server but an RMI stub that can be used to invoke the session bean from another server or a client application.
The J2EE server (like Glassfish or Oracle Weblogic) manages the life cycle of a stateless session bean unlike regular Java classes. The server decides when to create and remove bean instances, so the application never knows how many instances of a session bean class that is created, nor does it know when they are created or destroyed.
Since the server itself needs to initialize services for the bean before the business logic is invoked, and the bean itself most likely will need to make some initializations of itself,
the constructor is not a good place for that bean initialization code.
To allow both the server and the enterprise bean to make their initializations, EJBs support something called “lifecycle callback methods” that are annotated by the programmer and invoked by the server at various points in th bean’s life cycle.
For stateless session beans there are two lifecycle callbacks:
A stateless session beans lifetime is the lifetime of a single method within it. It can contain several methods, but they are completely independent of each other.
A stateless session bean cannot hold any data between calls from the client, it is designed to carry out independent operations very efficiently.
Stateless session beans may scale to large numbers of clients with minimal impact to overall server resources.
A stateless session bean contains of two parts.