2014-07-18 68 views
0

我有一個叫做RandomBean的SFSB,它有一個默認構造函數@PostConstruct,@PreDestroy@Remove方法。在構造函數中有一個簡單的計數器。InitialContext.doLookup調用Bean的構造函數兩次

@Stateful 
public class RandomBean { 

    public static int c = 0; 

    public static final Logger logger = Logger.getLogger(RandomBean.class); 

    private Random r; 

    private int cc; 

    public RandomBean() { 
     c += 1; 
     cc = c; 
     r = new Random(); 
     logger.info("Random constructed: " + cc); 
    } 

    @PostConstruct 
    public void init() { 
     logger.info("Random started: " + cc); 
    } 

    public int nextInt() { 
     logger.info("Random invoked: " + cc); 
     return r.nextInt(); 
    } 

    @PreDestroy 
    public void destroy() { 
     logger.info("Random destroyed: " + cc); 
    } 

    @Remove 
    public void remove() { 
     logger.info("removed: " + cc); 
    } 
} 

我也有對這個bean執行查找和調用其nextInt方法的servlet。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    logger.info("Doing get"); 
    try { 
     RandomBean r = InitialContext.doLookup("java:module/RandomBean"); 
     logger.info("get! " + r.nextInt()); 
     r.remove(); 
    } catch (NamingException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

什麼讓我困惑的是,RandomBean的構造似乎叫了兩聲:

02:13:09,558 INFO [org.sokolas.model.HelloServlet] (http-localhost/127.0.0.1:8080-1) Doing get 
02:13:09,559 INFO [org.sokolas.model.RandomBean] (http-localhost/127.0.0.1:8080-1) Random constructed: 1 
02:13:09,560 INFO [org.sokolas.model.RandomBean] (http-localhost/127.0.0.1:8080-1) Random constructed: 2 
02:13:09,561 INFO [org.sokolas.model.RandomBean] (http-localhost/127.0.0.1:8080-1) Random started: 2 
02:13:09,561 INFO [org.sokolas.model.RandomBean] (http-localhost/127.0.0.1:8080-1) Random invoked: 2 
02:13:09,562 INFO [org.sokolas.model.HelloServlet] (http-localhost/127.0.0.1:8080-1) get! -2028573462 
02:13:09,562 INFO [org.sokolas.model.RandomBean] (http-localhost/127.0.0.1:8080-1) removed: 2 
02:13:09,563 INFO [org.sokolas.model.RandomBean] (http-localhost/127.0.0.1:8080-1) Random destroyed: 2 

這種行爲是故意的嗎?我應該把所有的初始化放在@PostConstruct方法中,而不要使用構造函數嗎? 我正在使用JBoss EAP 6.2。

回答

1

容器可能決定預先創建bean實現的其他實例。 在實例創建時,它不綁定到任何客戶端會話。

您應該將所有初始化邏輯放入ejbCreate/@ Init或@PostConstruct方法中。 如果你看一下SFSB在EJB 3.1規範4.6.1中可能做什麼,你甚至會發現你不允許在構造函數中對容器服務進行任何調用,但是在回調函數中更多。

相關問題