【问题标题】:Factory method bean inheritance in Spring XML configurationSpring XML配置中的工厂方法bean继承
【发布时间】: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


    【解决方案1】:

    如下更改 id 为 parentController 的 bean:

    <bean id="parentController" class="factory.ControllerFactory" factory-bean="controllerFactory" factory-method="getController"> <constructor-arg index="0" value="OtherController"/> </bean>.

    试试这个可能会奏效。

    【讨论】:

    • 也传递构造函数参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    相关资源
    最近更新 更多