2011-06-15 31 views
0

我有下面的代碼動態依賴我的班內注射彈簧

public void startListeners() throws Exception { 
     List<QueueConfiguration> queueConfigs = queueConfigResolver.getQueueConfigurations(); 
     for(QueueConfiguration queueConfig : queueConfigs){ 
      //TODO : work on this make it more testable 
      ICustomListener readerListener = new MyCustomListener(queueConfig); 
      readerListeners.add(readerListener); 
      readerListener.start(); 
     } 

    } 

我使用Spring依賴注入(在此情況下,但總體來說)。現在這個代碼有兩個問題。

  1. 我不能爲每個創建的偵聽器進行模擬,而進行測試。
  2. 我不想使用ApplicationContext.getBean(),因爲它會有相同的影響。 AFAIK春天不能動態地做到這一點,但任何其他指針?
+2

你能解釋一下更詳細一點你想測試什麼嗎?隊列配置或偵聽器?爲什麼你不想完全使用applicationcontext.getbean? Spring不能動態地做什麼。這種情況下動態的意思是什麼? – Omnaest 2011-06-15 17:19:33

回答

0

至於我能理解,你想創建一個新的bean,而不是 ICustomListener readerListener =新MyCustomListener(queueConfig); 如果是這樣的情況下,創造了mycustomlistener一家工廠,利用

public abstract TestClient createTestClient(); 

創建你的bean,並在上下文將解決您的問題定義

<bean id="testClient" class="com.myproject.testbeans.TestClient" scope="prototype">  
</bean> 
<bean id="testClientFactory" class="com.myproject.testbeans.TestClientFactory"> 
    <lookup-method name="createTestClient" bean="testClient" /> 
</bean> 

。這樣,每次調用工廠的createTestClient方法時,都會創建一個新的bean並將其提供給您的代碼。但是,您必須通過setter而不是構造函數來提供配置對象。