eclipse + JBoss 5 + EJB3開發指南(4):Session Bean中的注釋方法

來源:互聯網
上載者:User

有時需要在Session Bean中初始化和釋放一些資源。這些工作應該在SessionBean的@PostConstruct和 @PreDestroy方法中進行。其中用@PostConstruct注釋的方法在SessionBean的構造方法調用之後以後EJB 容器在處理完一些其他工作後調用。用@PreDestroy注釋的方法在SessionBean的對象執行個體被EJB容器銷毀 之前調用。

除此之外,當有狀態的SessionBean存在一定時間未被調用時,EJB容器會將該SessionBean對象鈍化( Passivate),也就是儲存在硬碟中。當再次訪問時,EJB容器會激法該SessionBean。在這兩種情況下, EJB容器會分別調用SessionBean的@PrePassivate和@PostActivate方法。可以在@PrePassivate方法中將 sessionbean中的資源儲存或釋放,如開啟的資料庫連接等。在@PostActivate方法中可以恢複相應的資源 。如下面的代碼所示:

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;
    }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.