0
我读过,基于XML的Spring配置bean可以继承工厂方法。
我试图实现它:
控制器接口:Spring XML配置中的工厂方法bean继承
public interface Controller {
String method();
}
的ControllerFactory类:
public class ControllerFactory {
public Controller getController(String controllerName){
switch(controllerName){
case "OtherController":
return new OtherController();
case "SampleController":
return new SampleController();
default:
throw new IllegalArgumentException("Wrong controller name.");
}
}
}
SampleController实现:
public class SampleController implements Controller {
@Override
public String method() {
return "SampleController";
}
}
OtherController实现:
public class OtherController implements Controller {
@Override
public String method() {
return "OtherController";
}
}
但下面的XML配置:
<!--factory method inheritance -->
<bean id="controllerFactory" class="factory.ControllerFactory"/>
<bean id="parentController" abstract="true" factory-bean="controllerFactory" factory-method="getController"/>
<bean id="otherController" parent="parentController">
<constructor-arg index="0" value="OtherController"/>
</bean>
给出编译时错误:
No matching constructor found in class 'Controller'
我怎样才能改变它有工厂方法豆继承实施得当?
复制工厂方法配置子bean按预期工作:
<bean id="otherController" parent="parentController" factory-bean="controllerFactory" factory-method="getController">
<constructor-arg index="0" value="OtherController"/>
</bean>
也传递构造函数。 – SachinSarawgi