开发者

Dynamic Dependency Injection Spring

I have following code inside my class

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();
        }

    }

I am using Spring for dependency injectio开发者_如何学Gon(not in this case but overall). Now there two problems with this code.

  1. I cannot put mock for each of the listeners created, while testing.
  2. I dont want to use ApplicationContext.getBean() because it will have same affect. AFAIK spring cannot do this dynamically , but any other pointers?


As far as I can understand, you want to create a new bean instead of ICustomListener readerListener = new MyCustomListener(queueConfig); If that is the case, creating a factory for mycustomlistener and using

public abstract TestClient createTestClient();

to create your beans, and defining

<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> 

in your context will solve your problem. This way, every time the createTestClient method of the factory is called, a new bean is created and given to your code. However, you have to give the config object via a setter instead of the constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜