本文为原创,如需转载,请注明作者和出处,谢谢!
有时需要在Session Bean中初始化和释放一些资源。这些工作应该在SessionBean的@PostConstruct和@PreDestroy方法中进行。其中用 @PostConstruct注释的方法在SessionBean的构造方法调用之后以后EJB容器在处理完一些其他工作后调用。用 @PreDestroy注释的方法在SessionBean的对象实例被EJB容器销毁之前调用。
除此之外,当有状态的SessionBean存在一定时间未被调用时,EJB容器会将该SessionBean对象钝化(Passivate),也就是保 存在硬盘中。当再次访问时,EJB容器会激法该SessionBean。在这两种情况下,EJB容器会分别调用SessionBean的 @PrePassivate和@PostActivate方法。可以在@PrePassivate方法中将sessionbean中的资源保存或释放,如 打开的数据库连接等。在@PostActivate方法中可以恢复相应的资源。如下面的代码所示:
- packageservice;
- importjava.util.ArrayList;
- importjava.util.List;
- importjavax.annotation.PostConstruct;
- importjavax.annotation.PreDestroy;
- importjavax.annotation.Resource;
- importjavax.ejb.PostActivate;
- importjavax.ejb.PrePassivate;
- importjavax.ejb.SessionContext;
- importjavax.ejb.Stateful;
- @Stateless
- publicclassShoppingCartBeanimplementsShoppingCart
- {
- privateList<String>shoppingCart=newArrayList<String>();
- @Resource
- privateSessionContextsessionContext;
- publicShoppingCartBean()
- {
- System.out.println("constructor:"+sessionContext);
- }
- @PrePassivate
- publicvoidMyPassivate()
- {
- System.out.println("passivate");
- }
- @PostConstruct
- publicvoidinit()
- {
- System.out.println(sessionContext.getInvokedBusinessInterface());
- }
- @PreDestroy
- publicvoiddestory()
- {
- System.out.println("destory");
- }
- @PostActivate
- publicvoidstart()
- {
- System.out.println("start");
- }
- @Override
- publicvoidaddCommodity(Stringvalue)
- {
- shoppingCart.add(value);
- }
- @Override
- publicList<String>getCommodity()
- {
- returnshoppingCart;
- }
- }