2011-06-15 34 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而不是构造函数来提供配置对象。