我读过,在基于XML的Spring配置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按预期工作:
<bean id="otherController" parent="parentController" factory-bean="controllerFactory" factory-method="getController">
<constructor-arg index="0" value="OtherController"/>
</bean>
答案 0 :(得分:1)
更改标识为parentController
的bean,如下所示:
<bean id="parentController" class="factory.ControllerFactory" factory-bean="controllerFactory" factory-method="getController">
<constructor-arg index="0" value="OtherController"/>
</bean>
。
试试这个可行。