0

I have a builder class defined as below in a 3rd party library:

public class KeyBuilder {

private A a;
private B b;
private C c;

public KeyBuilder withA(final A a){
    this.a = a;
    return this;
}

public KeyBuilder withB(final B b){
    this.b = b;
    return this;
}

public KeyBuilder withC(final C c){
    this.c = c;
    return this;
}

public Key build() {
    return new Key(this.a, this.b, this.c);
}

}

I am trying to create an instance of Key using the builder with below spring configuration:

<!-- A -->
<bean id="A" class="com.example.A" />

<!-- B -->
<bean id="B" class="com.example.B" />

<!-- C -->
<bean id="C" class="com.example.C" />

<!-- KeyBuilder -->
<bean id="KeyBuilder" class="com.example.KeyBuilder">
    <property name="a" value="A"/>
    <property name="b" value="B"/>
    <property name="c" value="C"/>
</bean>

<!-- Key -->
<bean id="Key" factory-bean="KeyBuilder" factory-method="build" />

However, it fails with below error:

Error creating bean with name 'KeyBuilder' defined in URL [file:spring-config.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'a' of bean class [com.example.KeyBuilder]: Bean property 'a' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

As I understand it would just work if I change the method names in builder from 'withA/withB/withC' to 'setA/setB/setC' but I do not have that option as the library is managed by a 3rd party.

Could someone please suggest if there is a way to pass setter method in the property tag or an alternate way to solve the issue here.

randomcompiler
  • 309
  • 2
  • 14

1 Answers1

0

If you use annotation based configuration , you can easily do it by programmatically creating the Key inside the @Bean method as usual.

But assuming you can only use XML configuration , then you can implement a FactoryBean , which allow you to define how to create a bean programmatically:

public class KeyFactoryBean implements FactoryBean<Key> {

    private A a;
    private B b;
    private C c;

    public void setA(A a){
       this.a= a;
    }

    public void setB(B b){
       this.b= b;
    }

    public void setC(C c){
       this.c= c;
    }

    @Override
    public Key getObject() throws Exception {
        return new KeyBuilder()
                .withA(this.a)
                .withB(this.b)
                .withC(this.c)
                .build();
    }

    @Override
    public Class<?> getObjectType() {
        return Key.class;
    }
}

Then the XML configuration:

<bean id="Key" class="com.example.KeyFactoryBean">
    <property name="a" ref="A" />
    <property name="b" ref="B"/>
    <property name="c" ref="C" />
</bean>
Ken Chan
  • 84,777
  • 26
  • 143
  • 172