Michał Szewczyk
Michał Szewczyk

Reputation: 8168

Factory method bean inheritance in Spring XML configuration

I read, that in XML-based Spring configuration beans can inherit factory method.
I tried to implement it:

Controller interface:

public interface Controller {
    String method();
}

ControllerFactory class:

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 implementation:

public class SampleController implements Controller {
    @Override
    public String method() {
        return "SampleController";
    }
}

OtherController implementation:

public class OtherController implements Controller {
    @Override
    public String method() {
        return "OtherController";
    }
}

But the following XML configuration:

<!--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>

Gives compile-time error:

No matching constructor found in class 'Controller'

How can I change it to have factory method bean inheritance implemented properly?

Copying factory-method configuration to child bean works as expected:

<bean id="otherController" parent="parentController" factory-bean="controllerFactory" factory-method="getController">
    <constructor-arg index="0" value="OtherController"/>
</bean>

Upvotes: 0

Views: 688

Answers (1)

SachinSarawgi
SachinSarawgi

Reputation: 2692

Change bean with id parentController as follows:

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

Try this it may work.

Upvotes: 1

Related Questions