Spring Boot中RestTemplateBuilder方法不返回this,是否符合Builder模式?
Great question! Let's break this down clearly—yes, this implementation is fully compliant with the Builder design pattern; it just uses an immutable variant of the pattern, which is a perfectly valid (and often preferred) approach in framework design.
Here's the breakdown:
The core purpose of the Builder pattern is to separate the step-by-step construction of a complex object from its final representation. There’s no hard rule that mandates the builder must mutate itself and return this (the mutable builder style you might be used to). Immutable builders are a well-established variation that solves specific problems.
Immutable vs. Mutable Builders
- Mutable Builders (return
this): These reuse the same instance for each configuration step. They’re lightweight for one-off builds but aren’t thread-safe, and you can’t save intermediate builder states to reuse later (since modifying the builder changes it everywhere). - Immutable Builders (return new instances): Each method call creates a fresh builder instance with the updated configuration, leaving the original builder untouched. This approach offers two key benefits:
- Thread safety: No shared mutable state means multiple threads can use different builder instances without conflicts—critical for frameworks like Spring that handle concurrent requests.
- Reusability: You can keep a base builder with common configurations, then create derived builders with additional settings without altering the original. For example, you could have a base
RestTemplateBuilderwith default message converters, then fork it to add basic auth for one API client and OAuth interceptors for another.
Why Spring Boot Chooses This Approach
Looking at your example of the basicAuthorization method:
public RestTemplateBuilder basicAuthorization(String username, String password) { return new RestTemplateBuilder( this.detectRequestFactory, this.rootUri, this.messageConverters, this.requestFactory, this.uriTemplateHandler, this.errorHandler, new BasicAuthorizationInterceptor(username, password), this.restTemplateCustomizers, this.requestFactoryCustomizers, ... ); }
This creates a new RestTemplateBuilder with all the existing configuration plus the new BasicAuthorizationInterceptor. This is intentional—Spring Boot designs many of its builders this way to support safe concurrent use and give developers flexibility to fork configurations easily.
Final Takeaway
The Builder pattern is flexible, and immutable implementations are a legitimate, useful variation. Spring’s choice here aligns with best practices for framework design, prioritizing thread safety and reusability over minimal object creation overhead (which is negligible for short-lived builder instances).
内容的提问来源于stack exchange,提问作者Tim

