2013-10-25 67 views
0

我有一個生產者方法的Singleton EJB。無論如何鎖定@Produces方法

@javax.ejb.Singleton 
public class MyBean{ 

    private Something something; 

    @Produces 
    public MySomething getSomething() {    
      if(null == something){ 
       LOG.info("Initializing MySomething."); 
       something = new Something(); 
      } 
      return something; 
    } 
} 

我以爲這會鎖,但我看到這個"Initializing MySomething."在日誌中多次東西,然後拋出一個java.lang.StackOverflowError

所以看起來像我需要鎖定這個@Produces方法。

爲此可以使用java.util.concurrent.Semaphore嗎?

回答

1

我猜你真正想要的是這樣的:

@Produces @ApplicationScoped 
public MySomething getSomething() { 
    // .... 
} 

因爲你的生產方法並沒有一個明確的範圍,則默認爲@Dependent範圍,所以一個新的bean實例獲取每注射點創建。這就是爲什麼你會收到多條日誌消息。

+0

我相信這是我想要的。我會試一試。 – DarVar

1

另一種方法是在你的文章構造中創建Something,並簡單地返回它。 EJB單身人士意味着每個應用程序的單個實例

public class MyBean { 
    private Something something; 
    @PostConstruct 
    public void createSomething() { 
     this.something = new Something(); 
    } 
    @Produces 
    public Something getSomething() { 
     return this.something; 
    } 
} 
+0

好點。但是,難道你不能直接註釋該字段嗎?爲什麼額外的吸氣劑? –

+0

你可以。我總是發現方法生產者更清晰可讀。 –