2012-08-13 50 views
0

我可以擁有如下的工廠嗎?通過彈簧初始化我的工廠

public class Factory 
{ 
    private static Map<EnumXyz, IDAO> map = new HashMap<Sting, Object>(); 


    public static void init() 
    { 
     //how do i initialize my map through spring initialization 
    } 

    public static IDAO getDAO(EnumXyz dao) 
    { 
     if (map.containsKey(dao)) 
     return map.get(dao); 
     else 
     { 
      throw new IllegalArgumentException("dao not supported " + dao); 
     } 

     return null; 
    } 

} 
  1. 我怎麼照顧我廠的初始化通過春天?
  2. 建立工廠的這種方式是否正確?
  3. 任何其他更好的方法?

回答

0

我會實例化你的工廠作爲一個bean本身,並有一個實例它 - 不要讓所有東西都是靜態的。 Spring本身可以控制你的bean是否是單例(它將默認爲這樣)。

例如

public class Factory { 
    public Factory(final Map<String,Object} map) { 
     this.map = map; 
    } 
} 

和你的Spring配置:

<bean id="myFactory" class="Factory"> 
    <constructor-arg> 
     <util:map> 
     <!-- configure your map here, or reference it as a separate bean --> 
     <entry key="java.lang.String" value="key">....</entry> 
     </util:map> 
    </constructor-arg> 
</bean> 

在你的構造,通過其中在Spring配置定義自己的地圖。

+0

沒有得到你,你能詳細說明 – user978939 2012-08-13 14:13:16

+0

和工廠本身將單身課? – user978939 2012-08-13 14:16:02

+0

工廠可以從多個地方調用,所以我如何確保工廠只有一個實例? – user978939 2012-08-13 14:18:06

2
  1. 不要讓所有東西都是靜態的,特別是不要init()方法。
  2. 註釋你的豆@Component
  3. 註釋你的init()方法與@PostConstruct

現在,當Spring構造Factory類時,調用init()方法,爲它提供一個掛鉤來初始化自己。