我想根据特定类型创建bean。我是一个抽象类,它由两个具体类扩展,其对象我想通过基于类型的Factory(或任何其他最适合的方法)类来实例化。
public abstract class Helper{
public abstract boolean check();
}
public class C1 extends Helper{
public boolean check(){
//implementation here
}
}
public class C2 extends Helper{
public boolean check(){
//implementation here
}
}
public interface MyFactory{
public Helper create(){
}
应用context.xml中
<bean id=.../>
我应该如何通过XML依赖注入Spring来实现这一点?
此外,我尝试了ServiceLocatorFactoryBean方法,但这并没有帮助我传递所需类型的对象。点击此链接 - http://www.jcombat.com/spring/factory-implementation-using-servicelocatorfactorybean-in-spring
答案 0 :(得分:0)
实施工厂(例如MyFactoryImpl
),然后配置:
<bean id="myFactoryImpl" class="com.example.MyFactoryImpl" />
<bean id="c1"
factory-bean="myFactoryImpl"
factory-method="create"/>
示例工厂:
public class com.example.MyFactoryImpl implements MyFactory {
public Helper create(){return new C1()}
}
(Spring不需要MyFactory
接口)