问题描述
我有一个名为 MyInterface
的界面。实现 MyInterface
的类(让我们称之为 MyImplClass
)也实现 Runnable
接口所以我可以用它来实例化线程。这是我的代码。
I have an interface called MyInterface
. The class that implements MyInterface
(lets call it MyImplClass
) also implements the Runnable
interface so i can use it to instantiate threads. This is my code now.
for (OtherClass obj : someList) {
MyInterface myInter = new MyImplClass(obj);
Thread t = new Thread(myInter);
t.start();
}
我想要做的是在ApplicationContext.xml中声明实现类并为每次迭代获取一个新实例。所以我的代码看起来像这样:
What i want to do is to declare the implementing class in my ApplicationContext.xml and get a new instance for each iteration. So my code will look something like this:
for (OtherClass obj : someList) {
MyInterface myInter = // getting the implementation from elsewhere
Thread t = new Thread(myInter);
t.start();
}
我想尽可能保留IoC模式。
我该怎么办?
谢谢
I want to still keep the IoC pattern if possible.
How can i do so?
Thanks
推荐答案
您可以尝试使用弹簧范围原型的工厂模式,如下所示。定义一个抽象工厂类,它将为您提供 MyInterface
对象
You can try factory pattern with spring scope prototype like below. Define a Abstract Factory Class which will give you MyInterface
object
public abstract class MyInterfaceFactoryImpl implements MyInterfaceFactory {
@Override
public abstract MyInterface getMyInterface();
}
然后定义Spring bean.xml文件,如下所示。请注意 myinterface
bean被定义为原型(所以它总是会给你新实例)。
Then define the Spring bean.xml file as below. Please note myinterface
bean is defined as prototype ( So it will always give you new instance).
<bean name="myinterface" class="com.xxx.MyInterfaceImpl" scope="prototype"/>
然后使用工厂方法名称定义factorybean。
Then define the factorybean with factory method name.
<bean name="myinterfaceFactory" class="com.xxx.MyInterfaceFactoryImpl">
<lookup-method bean="myinterface" name="getMyInterface" />
</bean>
现在你可以调用 myinterfaceFactory
来获取新的实例。
Now you can call myinterfaceFactory
to get new instance.
for (OtherClass obj : someList) {
MyInterface myInter = myInterfaceFactory.getMyInterface();
Thread t = new Thread(myInter);
t.start();
}
这篇关于获取spring bean的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!