【发布时间】:2017-02-21 12:13:24
【问题描述】:
我读到,基于 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";
}
}
其他控制器实现:
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>
【问题讨论】:
标签: java xml spring inheritance javabeans