Sometimes you need to initialize and release some resources in the session bean. These efforts should be carried out in the @postconstruct and @PreDestroy methods of Sessionbean. Where the @postconstruct annotation method is called after a Sessionbean constructor call, after some other work has been processed by the EJB container. The @predestroy annotation method is invoked before the Sessionbean object instance is destroyed by the EJB container.
In addition, when a stateful sessionbean exists for a certain time, the EJB container will deactivate the Sessionbean object (passivate), which is saved on the hard disk. When accessed again, the EJB container Sessionbean the method. In both cases, the EJB container invokes the Sessionbean @prepassivate and @postactivate methods, respectively. You can save or release resources in the Sessionbean in the @prepassivate method, such as open database connections. The appropriate resources can be recovered in the @postactivate method. As shown in the following code:
Package service;
Import java.util.ArrayList;
Import java.util.List;
Import javax.annotation.PostConstruct;
Import Javax.annotation.PreDestroy;
Import Javax.annotation.Resource;
Import Javax.ejb.PostActivate;
Import Javax.ejb.PrePassivate;
Import Javax.ejb.SessionContext;
Import javax.ejb.Stateful;
@Stateless
public class Shoppingcartbean implements ShoppingCart
{
Private list<string> ShoppingCart = new arraylist<string> ();
@Resource
Private Sessioncontext Sessioncontext;
Public Shoppingcartbean ()
{
System.out.println ("constructor:" + Sessioncontext);
}
@PrePassivate
public void Mypassivate ()
{
System.out.println ("Passivate");
}
@PostConstruct
public void Init ()
{
System.out.println (Sessioncontext.getinvokedbusinessinterface ());
}
@PreDestroy
public void Destory ()
{
System.out.println ("Destory");
}
@PostActivate
public void Start ()
{
System.out.println ("Start");
}
@Override
public void Addcommodity (String value)
{
Shoppingcart.add (value);
}
@Override
Public list<string> getcommodity ()
{
return ShoppingCart;
}
}