Skip to content

HttpHeaders constructor should not be public or should not mutate original HttpHeaders #28336

@ryoheinagao

Description

@ryoheinagao

Problem

  1. When I use HttpHeaders, its constructors confuse me, because instance initialized from original header has same hashmap of original. For example, test code below will be failed. Calling a method of copy instance may affect original instance.
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;

public class HeaderTest {

    @Test
    void test() {
        var original = new HttpHeaders();
        var copy = new HttpHeaders(original);

        copy.add("key", "value");

        Assertions.assertFalse(original.containsKey("key"));
    }
}
  1. The javadoc says that the constructor I mentioned is for internal use in the spring fremework, but users can access it.
    /**
    * Construct a new, empty instance of the {@code HttpHeaders} object.
    * <p>This is the common constructor, using a case-insensitive map structure.
    */
    public HttpHeaders() {
    this(CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)));
    }
    /**
    * Construct a new {@code HttpHeaders} instance backed by an existing map.
    * <p>This constructor is available as an optimization for adapting to existing
    * headers map structures, primarily for internal use within the framework.
    * @param headers the headers map (expected to operate with case-insensitive keys)
    * @since 5.1
    */
    public HttpHeaders(MultiValueMap<String, String> headers) {
    Assert.notNull(headers, "MultiValueMap must not be null");
    this.headers = headers;
    }

Suggetion

So I suggest this confusional constructor is package-private not to be accessed from external the library or support immutableness of its hashmap field.

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: webIssues in web modules (web, webmvc, webflux, websocket)status: declinedA suggestion or change that we don't feel we should currently apply

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions