Search code examples
javaspringdesign-patternsbuilder

Dependency Injection And Fluent Design


Say you have a spring component like below with dependencies constructor injected (builder is a singleton):

@Component
public class houseBuilder{

     private WindowMaker windowMaker;
     private DoorMaker doorMaker;
     private RoofMaker roofMaker;

     @Autowired
     public houseBuilder(WindowsMaker wm, DoorMaker dm, RoofMaker rm){
            this.windowMaker = wm;
            this.doorMaker = dm;
            this.roofMaker = rm;
     }

     //Other methods omitted for brevity

}

However the house requires something called "foundation" that should be passed in through the constructor or set before making the house begins and foundation is not a spring bean. I'd like to use the builder pattern as well so I could do something like the below but I am unsure how to do this with spring. Something like the below is what I am after except I want to use spring:

Foundation foundation = new Foundation();

HouseBuilder hb = new HouseBuilder(foundation)
.windowMaker(args)
.doorMaker(args)
.roofMaker(args);

Any advice is appreciated.


Solution

  • Spring Dependency injection and fluent builders are not really designed to work together.

    The first is a way to set dependencies of an object in an "automatic" way via annotation or configuration.
    While the second is a way for clients of the class to specify how the object should be build.

    Automatic dependency injection and declarative construction are so really two distinct ways to create objects.

    As a side note, Spring dependency injection with constructor brings two major fluent builder benefits : no more cumbersome constructor to call as the injection is performed by the container and the object may be immutable as no setter are required.