获取spring bean的新实例

Mr *_* T. 8 java spring inversion-of-control

我有一个名为的界面MyInterface.实现的类MyInterface(允许调用它MyImplClass)也实现了Runnable接口,因此我可以使用它来实例化线程.这是我的代码.

for (OtherClass obj : someList) {
    MyInterface myInter = new MyImplClass(obj);
    Thread t = new Thread(myInter);
    t.start();
} 
Run Code Online (Sandbox Code Playgroud)

我想要做的是在我的ApplicationContext.xml中声明实现类,并为每次迭代获取一个新实例.所以我的代码看起来像这样:

for (OtherClass obj : someList) {
    MyInterface myInter = // getting the implementation from elsewhere
    Thread t = new Thread(myInter);
    t.start();
} 
Run Code Online (Sandbox Code Playgroud)

如果可能的话,我还想保留IoC模式.
我怎么能这样做?
谢谢

Him*_*ire 13

您可以尝试使用弹簧范围原型的工厂模式,如下所示.定义一个抽象工厂类,它将为您提供MyInterface对象

public abstract class MyInterfaceFactoryImpl implements MyInterfaceFactory {

@Override
public abstract MyInterface getMyInterface();

}
Run Code Online (Sandbox Code Playgroud)

然后定义Spring bean.xml文件,如下所示.请注意myinterfacebean被定义为原型(所以它总是会给你新的实例).

<bean name="myinterface" class="com.xxx.MyInterfaceImpl" scope="prototype"/>
Run Code Online (Sandbox Code Playgroud)

然后使用工厂方法名称定义factorybean.

<bean name="myinterfaceFactory" class="com.xxx.MyInterfaceFactoryImpl">
    <lookup-method bean="myinterface" name="getMyInterface" />
</bean>
Run Code Online (Sandbox Code Playgroud)

现在您可以调用myinterfaceFactory以获取新实例.

for (OtherClass obj : someList) {
        MyInterface myInter = myInterfaceFactory.getMyInterface();
        Thread t = new Thread(myInter);
        t.start();
}
Run Code Online (Sandbox Code Playgroud)