2011-07-19 60 views
0

我們使用spring來構造/注入我們的java bean。下面的代碼段:使用函數/構造函數參數創建單例(用於例如注入)

<bean id="myAppConfigs" class="my.cool.webapp.ApplicationConfig" scope="singleton"> 
    <constructor-arg value="8080" /> 
    <constructor-arg value="MyAppName1" /> 
</bean> 

我們使用單例模式在

public static ApplicationConfig getCurrentInstance(ServletContext sctx) { 
    if (instance == null) { 
       WebApplicationContext wac = null; 
       if (sctx != null) { 
        wac = WebApplicationContextUtils.getWebApplicationContext(sctx); 
       } 
return (ApplicationConfig) wac.getBean("myAppConfigs"); 

由於豆僅讀了一些性能,這是我總是懷疑可能有問題一樣。但我仍然很好奇線程安全的方式來實現它 當然有線程安全的Double Checked Locking with usage of volatile。 但是有沒有另外一種方法可能使用Initialization on demand holder idiom與函數/構造函數參數?

+0

這與JSF有什麼關係? – BalusC

回答

1
public static ApplicationConfig getCurrentInstance(ServletContext sctx) { 
    if (sctx == null) { 
    throw new AssertionError("ServletContext is null"); 
    } 
    WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sctx); 
    if (wac == null) { 
    throw new AssertionError("No ApplicationContext associated with ServletContext"); 
    } 
    return (ApplicationConfig) wac.getBean("myAppConfigs"); 
} 

這是很多線程安全的。更好的做法是儘量使用注入(通過註釋或XML bean定義),但這並非總是可行。

使用混合了單例模式的Spring(DI)和顯式線程同步是一種反模式,並不真正需要。 Spring bean工廠本身是線程安全的,因此您不需要在其上添加任何額外的鎖定/同步。

相關問題