title: Builder Pattern Using Spring Injected Resources
body: <p>I have a <em>Builder</em> that uses several resources that are injected via Spring. It looks similar to this:</p>
  
  <pre><code>import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Component;
  
  @Component
  public class SandBoxBuilder {
      private final SandUtil sandUtil;
      private Sand sand;
      private Box box;
  
      @Autowired
      public SandBoxBuilder(SandUtil sandUtil) {
          this.sandUtil = sandUtil;
      }
  
      public SandBoxBuilder setSand(Sand sand) {
          this.sand = sand;
          return this;
      }
  
      public SandBoxBuilder setBox(Box box) {
          this.box = box;
          return this;
      }
  
      public SandBox build() {
          SandBox sandBox = new SandBox(sand);
          sandUtil.changeBox(sandBox, box);
          return sandBox;
      }
  }
  </code></pre>
  
  <p>The problem I have with this is that it is not thread safe. I know that this builder should not be a singleton, but I am not sure how to use the spring injected resources (<code>SandUtil</code>) without wiring the builder up and injecting it where I use it. </p>
  
  <p>How can I implement a <strong>thread safe</strong> builder that utilizes singletons injected by spring? </p>
  
  <h2>Solution</h2>
  
  <p>Because of some architectural constraints I could not inject the utilities into my calling classes. I ended up implementing a factory builder bean that returns new instances of a builder that has references to the spring resources. </p>
  
  <p><strong>Solution Implementation</strong></p>
  
  <pre><code>@Component
  public class SandBoxBuilderFactory {
      private final SandUtil sandUtil;
  
      @Autowired
      public SandBoxBuilderFactory(SandUtil sandUtil) {
          this.sandUtil = sandUtil;
      }
  
      public Builder newBuilder(){
          return new Builder(sandUtil);
      }
  
      public static class Builder {
          private final SandUtil sandUtil;
          private Sand sand;
          private Box box;
  
          private Builder(SandUtil sandUtil) {
              this.sandUtil = sandUtil;
          }
  
          public Builder setSand(Sand sand) {
              this.sand = sand;
              return this;
          }
  
          public Builder setBox(Box box) {
              this.box = box;
              return this;
          }
  
          public SandBox build() {
              SandBox sandBox = new SandBox(sand);
              sandUtil.changeBox(sandBox, box);
              return sandBox;
          }
  
      }
  }
  </code></pre>
  
  <p><strong>Usage</strong></p>
  
  <pre><code>newBuilder().setBox(box).setSand(sand).build();
  </code></pre>