(Updated) How to use the Builder Pattern with Spring Injection?

TL; DR: How can I use Composition Pattern Builder with Spring IoC?

I am creating a Spring project that populates a table based on distribution parameters for some fields (i.e. 50% of records should be of type A, 40% of type B, 10% of type C. For each type, 50% should be of subtype 1. 20% of subtype 2, 10% of subtype 3, etc., etc.).

To speed up the creation of records, I have a RecordFactory that calculates the distribution for these parameters and returns a RecordBuilder list. Each RecordBuilder extends the Callable interface to process and return records at the same time:

ActivityDiagram

What I have been doing so far, considering only types A, B, and C, was creating a TypeABuilder, TypeBBuilder, and TypeCBuilder that returned different ProcessorFactory implementations for each type:

public class RecordFactory {
    @Inject
    private transient TypeABuilder aBuilder;
    @Inject
    private transient TypeBBuilder bBuilder;
    @Inject
    private transient TypeCBuilder cBuilder;

    public List<DataBuilder> getBuilders() {
        // calculates distribution for each type and add the builders accordingly
    }
}

      

But obviously this is bad design. As the project gets more complex, I need to have mxn classes for every possible combination.

The best design would be to use composition, create DataBuilders according to the required parameters. How can I do this without losing the benefits o Spring IoC?


Update:

I changed the way the RecordFactory ProcessorFactory is created. Instead of separate Builder objects, I have one Builder object that uses the Builder pattern to create a ProcessorFactory based on my needs:

@Component
@Scope("prototype")
public class Builder {
    private Type type;
    private Subtype subtype;

    public Builder setType(Type type) {`
        this.type = type;
        return this;
    }

    public setSubtype(Subtype subtype) {
        this.subtype = subtype;
        return this;
    }

    public ProcessorFactory createFactory() {
        return new ProcessorFactoryImpl(this);
    }
}

public class ProcessorFactoryImpl {
    @Inject
    private transient TypeProcessor typeProcessor;

    @Inject
    private transient SubtypeProcessor subtypeProcessor;

    public ProcessorFactoryImpl(Builder builder) {
        typeProcessor.setType(builder.getType());
        processors.add(typeProcessor);
        subtypeProcessor.setSubtype(builder.getSubtype());
        processors.add(subTypeProcessor);
    }
}

      

Now my problem is, when I create a new ProcessorFactoryImpl in my Builder, I cannot inject my processors. How do I use the builder pattern with Spring while maintaining this flexibility?

+3


source to share





All Articles