From 1b13146fa7755bdf4342231835c9fdc4d53a8dd8 Mon Sep 17 00:00:00 2001 From: Sharang Gupta Date: Tue, 13 Oct 2026 22:02:54 +0100 Subject: [PATCH 1/6] Send the nested objects of @SpringQueryMap as nested query parameters Fixes gh-442 A nested object of a `@SpringQueryMap` parameter was sent as its `toString()` value, such as `range=Range(from=1, to=2)`, which no server can bind. * Add `NestedObjectQueryMapEncoder`, a `QueryMapEncoder` decorator that sends a nested object as `range.from=1&range.to=2`, the objects of a collection or an array as `filters[0].name=status`, and the entries of a map as `attributes[color]=red`, following the property path notation that Spring MVC binds; a collection of simple values is still sent as repeated parameters * Add the opt-in `spring.cloud.openfeign.client.nested-query-map-enabled` property, disabled by default to keep the behaviour of the existing applications, which decorates the auto-configured `QueryMapEncoder` * Document the option in the `@SpringQueryMap` section Signed-off-by: Sharang Gupta --- .../ROOT/pages/spring-cloud-openfeign.adoc | 32 +++ .../openfeign/FeignClientProperties.java | 23 +- .../openfeign/FeignClientsConfiguration.java | 23 +- .../support/NestedObjectQueryMapEncoder.java | 135 +++++++++ .../querymap/NestedQueryMapTests.java | 256 ++++++++++++++++++ ...jectQueryMapEncoderConfigurationTests.java | 119 ++++++++ .../NestedObjectQueryMapEncoderTests.java | 255 +++++++++++++++++ 7 files changed, 839 insertions(+), 4 deletions(-) create mode 100644 spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java create mode 100644 spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapTests.java create mode 100644 spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderConfigurationTests.java create mode 100644 spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java diff --git a/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc b/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc index 28e323171..374dfc499 100644 --- a/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc +++ b/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc @@ -841,6 +841,38 @@ public interface DemoTemplate { If you need more control over the generated query parameter map, you can implement a custom `QueryMapEncoder` bean. +[[feign-querymap-nested-objects]] +==== Nested objects + +By default, a nested object of a `@SpringQueryMap` parameter is sent as the `toString()` value of the object. +You can set `spring.cloud.openfeign.client.nested-query-map-enabled` to `true` to send the fields of a nested object as nested query parameters instead, with the property path notation that Spring MVC binds: a nested object as `range.from=1&range.to=2`, the objects of a collection or an array as `filters[0].name=status`, and the entries of a `Map` as `attributes[color]=red`. +A collection of simple values, such as strings or numbers, is still sent as repeated query parameters. + +For example, with the following classes: + +[source,java,indent=0] +---- +public class Search { + private String query; + private Range price; + private List filters; + + // [Getters and setters omitted for brevity] +} + +public class Range { + private Integer from; + private Integer to; + + // [Getters and setters omitted for brevity] +} +---- + +a call to `demoEndpoint(@SpringQueryMap Search search)` sends `query=shoes&price.from=10&price.to=20&filters[0].name=color&filters[0].value=red`, which a Spring MVC handler can bind with `@ModelAttribute Search search`. + +The option is disabled by default, to keep the behaviour of the existing applications. +When it is enabled, the `QueryMapEncoder` that Spring Cloud OpenFeign auto-configures is decorated with the `NestedObjectQueryMapEncoder`, which you can also use to decorate a custom `QueryMapEncoder` bean. + [[hateoas-support]] === HATEOAS support diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java index ccb4005e0..4cde2f45e 100644 --- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java @@ -45,6 +45,7 @@ * @author Hyeonmin Park * @author Jasbir Singh * @author Dominique Villard + * @author Sharang Gupta */ @ConfigurationProperties("spring.cloud.openfeign.client") public class FeignClientProperties { @@ -66,6 +67,14 @@ public class FeignClientProperties { */ private boolean removeTrailingSlash; + /** + * If {@code true}, the nested objects of a {@code @SpringQueryMap} parameter are sent + * as nested query parameters (for example, {@code range.from=1&range.to=2}) instead + * of their {@code toString()} value, and the objects of a collection or an array as + * indexed query parameters (for example, {@code filters[0].name=status}). + */ + private boolean nestedQueryMapEnabled; + public boolean isDefaultToProperties() { return defaultToProperties; } @@ -106,6 +115,14 @@ public void setRemoveTrailingSlash(boolean removeTrailingSlash) { this.removeTrailingSlash = removeTrailingSlash; } + public boolean isNestedQueryMapEnabled() { + return nestedQueryMapEnabled; + } + + public void setNestedQueryMapEnabled(boolean nestedQueryMapEnabled) { + this.nestedQueryMapEnabled = nestedQueryMapEnabled; + } + @Override public boolean equals(Object o) { if (this == o) { @@ -117,12 +134,14 @@ public boolean equals(Object o) { FeignClientProperties that = (FeignClientProperties) o; return defaultToProperties == that.defaultToProperties && Objects.equals(defaultConfig, that.defaultConfig) && Objects.equals(config, that.config) && Objects.equals(decodeSlash, that.decodeSlash) - && Objects.equals(removeTrailingSlash, that.removeTrailingSlash); + && Objects.equals(removeTrailingSlash, that.removeTrailingSlash) + && nestedQueryMapEnabled == that.nestedQueryMapEnabled; } @Override public int hashCode() { - return Objects.hash(defaultToProperties, defaultConfig, config, decodeSlash, removeTrailingSlash); + return Objects.hash(defaultToProperties, defaultConfig, config, decodeSlash, removeTrailingSlash, + nestedQueryMapEnabled); } /** diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java index 97916b844..b8790fc44 100644 --- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java @@ -52,6 +52,7 @@ import org.springframework.cloud.openfeign.support.FeignEncoderProperties; import org.springframework.cloud.openfeign.support.FeignHttpMessageConverters; import org.springframework.cloud.openfeign.support.HttpMessageConverterCustomizer; +import org.springframework.cloud.openfeign.support.NestedObjectQueryMapEncoder; import org.springframework.cloud.openfeign.support.PageableSpringEncoder; import org.springframework.cloud.openfeign.support.PageableSpringQueryMapEncoder; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; @@ -79,6 +80,7 @@ * @author Olga Maciaszek-Sharma * @author Hyeonmin Park * @author Yanming Zhou + * @author Sharang Gupta */ @Configuration(proxyBeanMethods = false) public class FeignClientsConfiguration { @@ -127,7 +129,7 @@ public Encoder feignEncoder(ObjectProvider formWriterProvide @ConditionalOnMissingBean @ConditionalOnMissingClass("org.springframework.data.domain.Pageable") public QueryMapEncoder feignQueryMapEncoder() { - return new SpringFieldQueryMapEncoder(); + return withNestedObjectSupport(new SpringFieldQueryMapEncoder(), feignClientProperties); } @Bean @@ -178,6 +180,20 @@ private static Encoder springEncoder(ObjectProvider formWrit } } + /** + * Decorate the query map encoder with the {@link NestedObjectQueryMapEncoder} when + * the {@code spring.cloud.openfeign.client.nested-query-map-enabled} property is set. + * @param queryMapEncoder the query map encoder of the auto-configuration. + * @param properties the Feign client properties, if any. + * @return the query map encoder to use. + */ + static QueryMapEncoder withNestedObjectSupport(QueryMapEncoder queryMapEncoder, FeignClientProperties properties) { + if (properties != null && properties.isNestedQueryMapEnabled()) { + return new NestedObjectQueryMapEncoder(queryMapEncoder); + } + return queryMapEncoder; + } + private static class SpringPojoFormEncoder extends SpringFormEncoder { SpringPojoFormEncoder(AbstractFormWriter formWriter) { @@ -193,6 +209,9 @@ private static class SpringPojoFormEncoder extends SpringFormEncoder { @ConditionalOnClass({ Pageable.class, DataWebProperties.class }) static class SpringDataConfiguration { + @Autowired(required = false) + private FeignClientProperties feignClientProperties; + private final DataWebProperties dataWebProperties; SpringDataConfiguration(ObjectProvider dataWebProperties) { @@ -224,7 +243,7 @@ public QueryMapEncoder feignQueryMapEncoderPageable() { queryMapEncoder.setSizeParameter(dataWebProperties.getPageable().getSizeParameter()); queryMapEncoder.setSortParameter(dataWebProperties.getSort().getSortParameter()); } - return queryMapEncoder; + return withNestedObjectSupport(queryMapEncoder, feignClientProperties); } } diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java new file mode 100644 index 000000000..46e385aa0 --- /dev/null +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java @@ -0,0 +1,135 @@ +/* + * Copyright 2013-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.openfeign.support; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import feign.QueryMapEncoder; +import feign.codec.EncodeException; + +import org.springframework.beans.BeanUtils; +import org.springframework.util.Assert; + +/** + * A {@link QueryMapEncoder} that sends the nested objects of a query map parameter as + * nested query parameters, with the property path notation that Spring MVC binds. + *

+ * The query map is produced by the delegate encoder. Then, each value that is not a + * simple value (see {@link BeanUtils#isSimpleValueType(Class)}) is encoded with the + * delegate too, and its entries are added with the name of the value as a prefix: + *

    + *
  • a nested object: {@code range.from=1&range.to=2}
  • + *
  • the objects of a collection or an array: {@code filters[0].name=status}
  • + *
  • the entries of a map: {@code attributes[color]=red}
  • + *
+ * A collection of simple values is kept as is, so it is still sent as repeated query + * parameters, and an array of simple values is sent the same way. + * + * @author Sharang Gupta + * @since 5.1.0 + * @see org.springframework.cloud.openfeign.FeignClientProperties#isNestedQueryMapEnabled() + */ +public class NestedObjectQueryMapEncoder implements QueryMapEncoder { + + private final QueryMapEncoder delegate; + + public NestedObjectQueryMapEncoder(QueryMapEncoder delegate) { + Assert.notNull(delegate, "delegate must not be null"); + this.delegate = delegate; + } + + @Override + public Map encode(Object object) throws EncodeException { + if (object == null) { + return Collections.emptyMap(); + } + Map queryMap = new LinkedHashMap<>(); + Set path = Collections.newSetFromMap(new IdentityHashMap<>()); + path.add(object); + addAll(queryMap, "", delegate.encode(object), path); + return queryMap; + } + + private void addAll(Map queryMap, String prefix, Map values, Set path) { + values.forEach((name, value) -> add(queryMap, prefix + name, value, path)); + } + + private void add(Map queryMap, String name, Object value, Set path) { + if (value == null) { + return; + } + if (isSimpleValue(value)) { + queryMap.put(name, value); + } + else if (value instanceof Map map) { + map.forEach((key, entryValue) -> add(queryMap, name + "[" + key + "]", entryValue, path)); + } + else if (value instanceof Iterable || value.getClass().isArray()) { + addElements(queryMap, name, value, path); + } + else { + addNestedObject(queryMap, name, value, path); + } + } + + private void addElements(Map queryMap, String name, Object value, Set path) { + List elements = toList(value); + if (elements.stream().allMatch(element -> element == null || isSimpleValue(element))) { + // Feign sends an Iterable as repeated query parameters + queryMap.put(name, value instanceof Iterable ? value : elements); + return; + } + for (int index = 0; index < elements.size(); index++) { + add(queryMap, name + "[" + index + "]", elements.get(index), path); + } + } + + private void addNestedObject(Map queryMap, String name, Object value, Set path) { + if (!path.add(value)) { + throw new EncodeException("Cannot encode the query map: an object of type " + value.getClass().getName() + + " is nested in itself under '" + name + "'"); + } + addAll(queryMap, name + ".", delegate.encode(value), path); + path.remove(value); + } + + private static boolean isSimpleValue(Object value) { + return BeanUtils.isSimpleValueType(value.getClass()); + } + + private static List toList(Object value) { + List elements = new ArrayList<>(); + if (value instanceof Iterable iterable) { + iterable.forEach(elements::add); + } + else { + int length = Array.getLength(value); + for (int index = 0; index < length; index++) { + elements.add(Array.get(value, index)); + } + } + return elements; + } + +} diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapTests.java new file mode 100644 index 000000000..174aeb045 --- /dev/null +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapTests.java @@ -0,0 +1,256 @@ +/* + * Copyright 2013-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.openfeign.querymap; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.Test; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.cloud.client.DefaultServiceInstance; +import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient; +import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier; +import org.springframework.cloud.loadbalancer.support.ServiceInstanceListSuppliers; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.SpringQueryMap; +import org.springframework.cloud.openfeign.test.NoSecurityConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RestController; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +/** + * Tests that the nested objects of a {@link SpringQueryMap} parameter are sent as nested + * query parameters that Spring MVC binds back. + * + * @author Sharang Gupta + */ +@SpringBootTest(classes = NestedQueryMapTests.Application.class, webEnvironment = RANDOM_PORT, + value = { "spring.application.name=nestedquerymaptest", "spring.jmx.enabled=false", + "spring.cloud.openfeign.client.nested-query-map-enabled=true" }) +@DirtiesContext +class NestedQueryMapTests { + + @Autowired + private SearchClient searchClient; + + @Test + void nestedObjectsAreSentAsNestedQueryParameters() { + Map> parameters = this.searchClient.parameters(search()); + + assertThat(parameters).containsOnly(Map.entry("query", List.of("shoes")), + Map.entry("price.from", List.of("10")), Map.entry("price.to", List.of("20")), + Map.entry("filters[0].name", List.of("color")), Map.entry("filters[0].value", List.of("red")), + Map.entry("filters[1].name", List.of("size")), Map.entry("filters[1].value", List.of("42")), + Map.entry("tags", List.of("sale", "new"))); + } + + @Test + void nestedQueryParametersAreBoundByTheServer() { + SearchRequest bound = this.searchClient.echo(search()); + + assertThat(bound.getQuery()).isEqualTo("shoes"); + assertThat(bound.getPrice().getFrom()).isEqualTo(10); + assertThat(bound.getPrice().getTo()).isEqualTo(20); + assertThat(bound.getFilters()).hasSize(2); + assertThat(bound.getFilters().get(1).getName()).isEqualTo("size"); + assertThat(bound.getFilters().get(1).getValue()).isEqualTo("42"); + assertThat(bound.getTags()).containsExactly("sale", "new"); + } + + private static SearchRequest search() { + SearchRequest request = new SearchRequest(); + request.setQuery("shoes"); + request.setPrice(new Range(10, 20)); + request.setFilters(List.of(new Filter("color", "red"), new Filter("size", "42"))); + request.setTags(List.of("sale", "new")); + return request; + } + + @FeignClient("local") + interface SearchClient { + + @GetMapping("/search/parameters") + Map> parameters(@SpringQueryMap SearchRequest request); + + @GetMapping("/search/echo") + SearchRequest echo(@SpringQueryMap SearchRequest request); + + } + + @RestController + static class SearchController { + + @GetMapping("/search/parameters") + Map> parameters(HttpServletRequest request) { + Map> parameters = new TreeMap<>(); + request.getParameterMap().forEach((name, values) -> parameters.put(name, List.of(values))); + return parameters; + } + + @GetMapping("/search/echo") + SearchRequest echo(@ModelAttribute SearchRequest request) { + return request; + } + + } + + @EnableFeignClients(clients = SearchClient.class) + @LoadBalancerClient(name = "local", configuration = LocalClientConfiguration.class) + @SpringBootApplication + @Import({ NoSecurityConfiguration.class, SearchController.class }) + static class Application { + + } + + @Configuration(proxyBeanMethods = false) + static class LocalClientConfiguration { + + @LocalServerPort + private int port = 0; + + @Bean + public ServiceInstanceListSupplier staticServiceInstanceListSupplier() { + return ServiceInstanceListSuppliers.from("local", + new DefaultServiceInstance("local-1", "local", "localhost", port, false)); + } + + } + + public static class SearchRequest { + + private String query; + + private Range price; + + private List filters = new ArrayList<>(); + + private List tags = new ArrayList<>(); + + public String getQuery() { + return query; + } + + public void setQuery(String query) { + this.query = query; + } + + public Range getPrice() { + return price; + } + + public void setPrice(Range price) { + this.price = price; + } + + public List getFilters() { + return filters; + } + + public void setFilters(List filters) { + this.filters = filters; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + } + + public static class Range { + + private Integer from; + + private Integer to; + + Range() { + } + + Range(Integer from, Integer to) { + this.from = from; + this.to = to; + } + + public Integer getFrom() { + return from; + } + + public void setFrom(Integer from) { + this.from = from; + } + + public Integer getTo() { + return to; + } + + public void setTo(Integer to) { + this.to = to; + } + + } + + public static class Filter { + + private String name; + + private String value; + + Filter() { + } + + Filter(String name, String value) { + this.name = name; + this.value = value; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } + +} diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderConfigurationTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderConfigurationTests.java new file mode 100644 index 000000000..fd66173f6 --- /dev/null +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderConfigurationTests.java @@ -0,0 +1,119 @@ +/* + * Copyright 2013-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.openfeign.support; + +import java.util.Map; + +import feign.QueryMapEncoder; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.openfeign.FeignClientFactory; +import org.springframework.test.annotation.DirtiesContext; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +/** + * Tests for the {@code spring.cloud.openfeign.client.nested-query-map-enabled} property. + * + * @author Sharang Gupta + */ +class NestedObjectQueryMapEncoderConfigurationTests { + + @Nested + @SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = RANDOM_PORT, + value = { "spring.application.name=nestedquerymaptest", "spring.jmx.enabled=false", + "spring.cloud.openfeign.client.nested-query-map-enabled=true" }) + @DirtiesContext + class WhenEnabled { + + @Autowired + private FeignClientFactory context; + + @Test + void queryMapEncoderSendsNestedObjectsAsNestedQueryParameters() { + QueryMapEncoder encoder = this.context.getInstance("foo", QueryMapEncoder.class); + + assertThat(encoder).isInstanceOf(NestedObjectQueryMapEncoder.class); + assertThat(encoder.encode(new Search(new Range(1, 2)))).containsOnly(Map.entry("price.from", 1), + Map.entry("price.to", 2)); + } + + } + + @Nested + @SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = RANDOM_PORT, + value = { "spring.application.name=nestedquerymaptest", "spring.jmx.enabled=false" }) + @DirtiesContext + class WhenDisabled { + + @Autowired + private FeignClientFactory context; + + @Test + void queryMapEncoderIsUnchangedByDefault() { + QueryMapEncoder encoder = this.context.getInstance("foo", QueryMapEncoder.class); + + assertThat(encoder).isNotInstanceOf(NestedObjectQueryMapEncoder.class); + assertThat(encoder.encode(new Search(new Range(1, 2)))).containsOnlyKeys("price"); + } + + } + + /** + * The Spring Data query map encoder invokes the getters reflectively, so the classes + * must be public. + */ + public static class Search { + + private final Range price; + + Search(Range price) { + this.price = price; + } + + public Range getPrice() { + return price; + } + + } + + public static class Range { + + private final Integer from; + + private final Integer to; + + Range(Integer from, Integer to) { + this.from = from; + this.to = to; + } + + public Integer getFrom() { + return from; + } + + public Integer getTo() { + return to; + } + + } + +} diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java new file mode 100644 index 000000000..65b774aab --- /dev/null +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java @@ -0,0 +1,255 @@ +/* + * Copyright 2013-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.openfeign.support; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import feign.Param; +import feign.QueryMapEncoder; +import feign.codec.EncodeException; +import org.junit.jupiter.api.Test; + +import org.springframework.data.domain.PageRequest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +/** + * Tests for {@link NestedObjectQueryMapEncoder}. + * + * @author Sharang Gupta + */ +class NestedObjectQueryMapEncoderTests { + + private final QueryMapEncoder encoder = new NestedObjectQueryMapEncoder(new SpringFieldQueryMapEncoder()); + + @Test + void flatObjectIsEncodedAsBefore() { + Search search = new Search(); + search.query = "shoes"; + search.page = 2; + + assertThat(encoder.encode(search)).containsOnly(Map.entry("query", "shoes"), Map.entry("page", 2)); + } + + @Test + void nestedObjectIsEncodedWithThePropertyPath() { + Search search = new Search(); + search.price = new Range(10, 20); + + assertThat(encoder.encode(search)).containsOnly(Map.entry("price.from", 10), Map.entry("price.to", 20)); + } + + @Test + void deeplyNestedObjectsAreEncodedWithTheFullPropertyPath() { + Search search = new Search(); + search.price = new Range(10, 20); + search.price.currency = new Currency("EUR"); + + assertThat(encoder.encode(search)).containsEntry("price.currency.code", "EUR"); + } + + @Test + void objectsOfACollectionAreEncodedWithTheirIndex() { + Search search = new Search(); + search.filters = List.of(new Filter("color", "red"), new Filter("size", "42")); + + assertThat(encoder.encode(search)).containsOnly(Map.entry("filters[0].name", "color"), + Map.entry("filters[0].value", "red"), Map.entry("filters[1].name", "size"), + Map.entry("filters[1].value", "42")); + } + + @Test + void objectsOfAnArrayAreEncodedWithTheirIndex() { + Search search = new Search(); + search.ranges = new Range[] { new Range(1, 2), new Range(3, 4) }; + + assertThat(encoder.encode(search)).containsOnly(Map.entry("ranges[0].from", 1), Map.entry("ranges[0].to", 2), + Map.entry("ranges[1].from", 3), Map.entry("ranges[1].to", 4)); + } + + @Test + void collectionOfSimpleValuesIsKeptAsRepeatedParameters() { + Search search = new Search(); + search.tags = List.of("sale", "new"); + + assertThat(encoder.encode(search)).containsOnly(Map.entry("tags", List.of("sale", "new"))); + } + + @Test + void arrayOfSimpleValuesIsSentAsRepeatedParameters() { + Search search = new Search(); + search.ids = new int[] { 1, 2 }; + + assertThat(encoder.encode(search)).containsOnly(Map.entry("ids", List.of(1, 2))); + } + + @Test + void entriesOfAMapAreEncodedWithTheirKey() { + Search search = new Search(); + search.attributes = new LinkedHashMap<>(); + search.attributes.put("color", "red"); + search.attributes.put("price", new Range(10, 20)); + + assertThat(encoder.encode(search)).containsOnly(Map.entry("attributes[color]", "red"), + Map.entry("attributes[price].from", 10), Map.entry("attributes[price].to", 20)); + } + + @Test + void simpleValueTypesAreNotNested() { + Search search = new Search(); + search.id = UUID.fromString("0f9a8a9e-6d8c-4c0a-9f8e-4b3c2a1d0e9f"); + search.since = LocalDate.of(2026, 10, 13); + search.amount = new BigDecimal("9.99"); + search.status = Status.OPEN; + + assertThat(encoder.encode(search)).containsOnly(Map.entry("id", search.id), Map.entry("since", search.since), + Map.entry("amount", search.amount), Map.entry("status", Status.OPEN)); + } + + @Test + void nullNestedObjectIsSkipped() { + Search search = new Search(); + search.query = "shoes"; + search.price = null; + + assertThat(encoder.encode(search)).containsOnly(Map.entry("query", "shoes")); + } + + @Test + void nullObjectIsEncodedAsAnEmptyMap() { + assertThat(encoder.encode(null)).isEmpty(); + } + + @Test + void parameterAliasOfANestedFieldIsHonored() { + Search search = new Search(); + search.price = new Range(10, 20); + search.price.unit = "cents"; + + assertThat(encoder.encode(search)).containsEntry("price.currency_unit", "cents"); + } + + @Test + void objectNestedInItselfIsRejected() { + Node parent = new Node(); + Node child = new Node(); + parent.child = child; + child.parent = parent; + + assertThatExceptionOfType(EncodeException.class).isThrownBy(() -> encoder.encode(parent)) + .withMessageContaining("nested in itself") + .withMessageContaining("child.parent"); + } + + @Test + void worksWithThePageableQueryMapEncoder() { + QueryMapEncoder pageableEncoder = new NestedObjectQueryMapEncoder(new PageableSpringQueryMapEncoder()); + + assertThat(pageableEncoder.encode(PageRequest.of(1, 10))).containsOnly(Map.entry("page", 1), + Map.entry("size", 10)); + } + + enum Status { + + OPEN, CLOSED + + } + + static class Search { + + String query; + + Integer page; + + UUID id; + + LocalDate since; + + BigDecimal amount; + + Status status; + + Range price; + + Range[] ranges; + + List filters; + + List tags; + + int[] ids; + + Map attributes; + + } + + static class Range { + + Integer from; + + Integer to; + + Currency currency; + + @Param("currency_unit") + String unit; + + Range(Integer from, Integer to) { + this.from = from; + this.to = to; + } + + } + + static class Currency { + + String code; + + Currency(String code) { + this.code = code; + } + + } + + static class Filter { + + String name; + + String value; + + Filter(String name, String value) { + this.name = name; + this.value = value; + } + + } + + static class Node { + + Node parent; + + Node child; + + } + +} From 57b3d87f4cd78e320c41260371eeaf9a70e425d2 Mon Sep 17 00:00:00 2001 From: Sharang Gupta Date: Thu, 15 Oct 2026 17:13:02 +0100 Subject: [PATCH 2/6] Reject query map values nested in themselves Only nested objects were tracked while encoding, so a map, a collection or an array that contains itself, directly or through other values, recursed until a StackOverflowError. * Track every map, collection, array and nested object on the current path and reject one that is already on it with an EncodeException. * Test a map, a list and an array that contain themselves, a cycle below the query map object, and a map referenced twice, which is not a cycle. Signed-off-by: Sharang Gupta --- .../support/NestedObjectQueryMapEncoder.java | 29 ++++---- .../NestedObjectQueryMapEncoderTests.java | 67 +++++++++++++++++++ 2 files changed, 84 insertions(+), 12 deletions(-) diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java index 46e385aa0..122c3c434 100644 --- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java @@ -44,7 +44,9 @@ *
  • the entries of a map: {@code attributes[color]=red}
  • * * A collection of simple values is kept as is, so it is still sent as repeated query - * parameters, and an array of simple values is sent the same way. + * parameters, and an array of simple values is sent the same way. A value that is nested + * in itself, directly or through other values, is rejected with an + * {@link EncodeException}. * * @author Sharang Gupta * @since 5.1.0 @@ -81,15 +83,27 @@ private void add(Map queryMap, String name, Object value, Set map) { + addNested(queryMap, name, value, path); + path.remove(value); + } + + private void addNested(Map queryMap, String name, Object value, Set path) { + if (value instanceof Map map) { map.forEach((key, entryValue) -> add(queryMap, name + "[" + key + "]", entryValue, path)); } else if (value instanceof Iterable || value.getClass().isArray()) { addElements(queryMap, name, value, path); } else { - addNestedObject(queryMap, name, value, path); + addAll(queryMap, name + ".", delegate.encode(value), path); } } @@ -105,15 +119,6 @@ private void addElements(Map queryMap, String name, Object value } } - private void addNestedObject(Map queryMap, String name, Object value, Set path) { - if (!path.add(value)) { - throw new EncodeException("Cannot encode the query map: an object of type " + value.getClass().getName() - + " is nested in itself under '" + name + "'"); - } - addAll(queryMap, name + ".", delegate.encode(value), path); - path.remove(value); - } - private static boolean isSimpleValue(Object value) { return BeanUtils.isSimpleValueType(value.getClass()); } diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java index 65b774aab..5bcfdf8f7 100644 --- a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java @@ -18,6 +18,7 @@ import java.math.BigDecimal; import java.time.LocalDate; +import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -161,6 +162,64 @@ void objectNestedInItselfIsRejected() { .withMessageContaining("child.parent"); } + @Test + void mapNestedInItselfIsRejected() { + Search search = new Search(); + search.attributes = new LinkedHashMap<>(); + search.attributes.put("self", search.attributes); + + assertThatExceptionOfType(EncodeException.class).isThrownBy(() -> encoder.encode(search)) + .withMessageContaining("nested in itself") + .withMessageContaining("attributes[self]"); + } + + @Test + void collectionNestedInItselfIsRejected() { + Holder holder = new Holder(); + holder.items = new ArrayList<>(); + holder.items.add(holder.items); + + assertThatExceptionOfType(EncodeException.class).isThrownBy(() -> encoder.encode(holder)) + .withMessageContaining("nested in itself") + .withMessageContaining("items[0]"); + } + + @Test + void arrayNestedInItselfIsRejected() { + Holder holder = new Holder(); + holder.elements = new Object[1]; + holder.elements[0] = holder.elements; + + assertThatExceptionOfType(EncodeException.class).isThrownBy(() -> encoder.encode(holder)) + .withMessageContaining("nested in itself") + .withMessageContaining("elements[0]"); + } + + @Test + void cycleBelowTheQueryMapObjectIsRejected() { + List items = new ArrayList<>(); + Search search = new Search(); + search.attributes = new LinkedHashMap<>(); + search.attributes.put("items", items); + items.add(search.attributes); + + assertThatExceptionOfType(EncodeException.class).isThrownBy(() -> encoder.encode(search)) + .withMessageContaining("nested in itself") + .withMessageContaining("attributes[items][0]"); + } + + @Test + void mapReferencedTwiceIsEncodedTwice() { + Map shared = Map.of("color", "red"); + Search search = new Search(); + search.attributes = new LinkedHashMap<>(); + search.attributes.put("front", shared); + search.attributes.put("back", shared); + + assertThat(encoder.encode(search)).containsOnly(Map.entry("attributes[front][color]", "red"), + Map.entry("attributes[back][color]", "red")); + } + @Test void worksWithThePageableQueryMapEncoder() { QueryMapEncoder pageableEncoder = new NestedObjectQueryMapEncoder(new PageableSpringQueryMapEncoder()); @@ -244,6 +303,14 @@ static class Filter { } + static class Holder { + + List items; + + Object[] elements; + + } + static class Node { Node parent; From b72671a17240f7676625e4248d71e9a9c0696218 Mon Sep 17 00:00:00 2001 From: Sharang Gupta Date: Thu, 15 Oct 2026 22:23:51 +0100 Subject: [PATCH 3/6] Keep JDK values and mixed collections as is Following the review: - Only introspect the types outside java.* and javax.*. The values of the other JDK types that are not simple value types, such as an Optional, a Duration or a Currency, are kept as is, as without the option, instead of failing to be encoded as nested objects. - Index the elements of a collection or an array only when all of them are nested objects. A collection with simple values is kept as is, so a simple value is always sent as a repeated query parameter, whatever the other elements are. A list of lists is sent as items[0]=s&items[0]=m, which Spring MVC binds, and the integration test now covers it. - Reject a map key with a square bracket, which the property path of its entry cannot hold, with an EncodeException. Signed-off-by: Sharang Gupta --- .../ROOT/pages/spring-cloud-openfeign.adoc | 4 +- .../support/NestedObjectQueryMapEncoder.java | 51 ++++++++++++++----- .../querymap/NestedQueryMapTests.java | 15 +++++- .../NestedObjectQueryMapEncoderTests.java | 47 +++++++++++++++++ 4 files changed, 102 insertions(+), 15 deletions(-) diff --git a/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc b/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc index 374dfc499..29d5f0df1 100644 --- a/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc +++ b/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc @@ -846,7 +846,9 @@ If you need more control over the generated query parameter map, you can impleme By default, a nested object of a `@SpringQueryMap` parameter is sent as the `toString()` value of the object. You can set `spring.cloud.openfeign.client.nested-query-map-enabled` to `true` to send the fields of a nested object as nested query parameters instead, with the property path notation that Spring MVC binds: a nested object as `range.from=1&range.to=2`, the objects of a collection or an array as `filters[0].name=status`, and the entries of a `Map` as `attributes[color]=red`. -A collection of simple values, such as strings or numbers, is still sent as repeated query parameters. +Simple values, such as strings, numbers or dates, and the values of the other JDK types, such as an `Optional` or a `Duration`, are sent as before. +A collection or an array is indexed only when all its elements are nested objects, so a collection with simple values, such as a `List`, is still sent as repeated query parameters. +A `Map` key with a square bracket cannot be written in the property path of its entry, so it is rejected with an `EncodeException`. For example, with the following classes: diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java index 122c3c434..6d1e68c53 100644 --- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java @@ -23,6 +23,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import feign.QueryMapEncoder; @@ -35,18 +36,21 @@ * A {@link QueryMapEncoder} that sends the nested objects of a query map parameter as * nested query parameters, with the property path notation that Spring MVC binds. *

    - * The query map is produced by the delegate encoder. Then, each value that is not a - * simple value (see {@link BeanUtils#isSimpleValueType(Class)}) is encoded with the - * delegate too, and its entries are added with the name of the value as a prefix: + * The query map is produced by the delegate encoder. Then, each nested object, that is a + * value that is neither a simple value (see {@link BeanUtils#isSimpleValueType(Class)}) + * nor of a {@code java.*} or {@code javax.*} type, is encoded with the delegate too, and + * its entries are added with the name of the value as a prefix: *

      *
    • a nested object: {@code range.from=1&range.to=2}
    • *
    • the objects of a collection or an array: {@code filters[0].name=status}
    • *
    • the entries of a map: {@code attributes[color]=red}
    • *
    - * A collection of simple values is kept as is, so it is still sent as repeated query - * parameters, and an array of simple values is sent the same way. A value that is nested - * in itself, directly or through other values, is rejected with an - * {@link EncodeException}. + * Simple values and the values of other JDK types, such as an {@code Optional} or a + * {@code Duration}, are kept as is. A collection or an array is encoded with the index of + * its elements only when none of them is such a value, so a collection that has some, + * such as a {@code List}, is still sent as repeated query parameters. A map key + * with a square bracket, and a value that is nested in itself, directly or through other + * values, are rejected with an {@link EncodeException}. * * @author Sharang Gupta * @since 5.1.0 @@ -81,7 +85,7 @@ private void add(Map queryMap, String name, Object value, Set queryMap, String name, Object value, Set queryMap, String name, Object value, Set path) { if (value instanceof Map map) { - map.forEach((key, entryValue) -> add(queryMap, name + "[" + key + "]", entryValue, path)); + map.forEach((key, entryValue) -> add(queryMap, name + "[" + mapKey(name, key) + "]", entryValue, path)); } else if (value instanceof Iterable || value.getClass().isArray()) { addElements(queryMap, name, value, path); @@ -109,8 +113,9 @@ else if (value instanceof Iterable || value.getClass().isArray()) { private void addElements(Map queryMap, String name, Object value, Set path) { List elements = toList(value); - if (elements.stream().allMatch(element -> element == null || isSimpleValue(element))) { - // Feign sends an Iterable as repeated query parameters + if (!areAllNested(elements)) { + // A plain value has no property path to index, so keep the elements as Feign + // sends them: an Iterable as repeated query parameters queryMap.put(name, value instanceof Iterable ? value : elements); return; } @@ -119,8 +124,28 @@ private void addElements(Map queryMap, String name, Object value } } - private static boolean isSimpleValue(Object value) { - return BeanUtils.isSimpleValueType(value.getClass()); + private static String mapKey(String name, Object key) { + String mapKey = String.valueOf(key); + if (mapKey.indexOf('[') >= 0 || mapKey.indexOf(']') >= 0) { + throw new EncodeException("Cannot encode the query map: the key '" + mapKey + "' of the map under '" + name + + "' has a square bracket, which the property path of its entry cannot hold"); + } + return mapKey; + } + + private static boolean areAllNested(List elements) { + List presentElements = elements.stream().filter(Objects::nonNull).toList(); + return !presentElements.isEmpty() + && presentElements.stream().noneMatch(NestedObjectQueryMapEncoder::isPlainValue); + } + + private static boolean isPlainValue(Object value) { + if (value instanceof Map || value instanceof Iterable || value.getClass().isArray()) { + return false; + } + String typeName = value.getClass().getName(); + return BeanUtils.isSimpleValueType(value.getClass()) || typeName.startsWith("java.") + || typeName.startsWith("javax."); } private static List toList(Object value) { diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapTests.java index 174aeb045..e67c51a45 100644 --- a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapTests.java @@ -70,7 +70,8 @@ void nestedObjectsAreSentAsNestedQueryParameters() { Map.entry("price.from", List.of("10")), Map.entry("price.to", List.of("20")), Map.entry("filters[0].name", List.of("color")), Map.entry("filters[0].value", List.of("red")), Map.entry("filters[1].name", List.of("size")), Map.entry("filters[1].value", List.of("42")), - Map.entry("tags", List.of("sale", "new"))); + Map.entry("tags", List.of("sale", "new")), Map.entry("groups[0]", List.of("s", "m")), + Map.entry("groups[1]", List.of("l"))); } @Test @@ -84,6 +85,7 @@ void nestedQueryParametersAreBoundByTheServer() { assertThat(bound.getFilters().get(1).getName()).isEqualTo("size"); assertThat(bound.getFilters().get(1).getValue()).isEqualTo("42"); assertThat(bound.getTags()).containsExactly("sale", "new"); + assertThat(bound.getGroups()).containsExactly(List.of("s", "m"), List.of("l")); } private static SearchRequest search() { @@ -92,6 +94,7 @@ private static SearchRequest search() { request.setPrice(new Range(10, 20)); request.setFilters(List.of(new Filter("color", "red"), new Filter("size", "42"))); request.setTags(List.of("sale", "new")); + request.setGroups(List.of(List.of("s", "m"), List.of("l"))); return request; } @@ -155,6 +158,8 @@ public static class SearchRequest { private List tags = new ArrayList<>(); + private List> groups = new ArrayList<>(); + public String getQuery() { return query; } @@ -179,6 +184,14 @@ public void setFilters(List filters) { this.filters = filters; } + public List> getGroups() { + return groups; + } + + public void setGroups(List> groups) { + this.groups = groups; + } + public List getTags() { return tags; } diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java index 5bcfdf8f7..26ed5181c 100644 --- a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java @@ -17,11 +17,13 @@ package org.springframework.cloud.openfeign.support; import java.math.BigDecimal; +import java.time.Duration; import java.time.LocalDate; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; import feign.Param; @@ -127,6 +129,45 @@ void simpleValueTypesAreNotNested() { Map.entry("amount", search.amount), Map.entry("status", Status.OPEN)); } + @Test + void jdkTypesThatAreNotSimpleValueTypesAreNotNested() { + Search search = new Search(); + search.timeout = Duration.ofSeconds(5); + search.currency = java.util.Currency.getInstance("EUR"); + search.nickname = Optional.of("shopper"); + + assertThat(encoder.encode(search)).containsOnly(Map.entry("timeout", search.timeout), + Map.entry("currency", search.currency), Map.entry("nickname", search.nickname)); + } + + @Test + void collectionThatMixesSimpleValuesAndObjectsIsKeptAsIs() { + Holder holder = new Holder(); + holder.items = List.of("color", new Filter("size", "42")); + + assertThat(encoder.encode(holder)).containsOnly(Map.entry("items", holder.items)); + } + + @Test + void collectionsOfACollectionAreEncodedWithTheirIndexAsRepeatedParameters() { + Holder holder = new Holder(); + holder.items = List.of(List.of("s", "m"), List.of("l")); + + assertThat(encoder.encode(holder)).containsOnly(Map.entry("items[0]", List.of("s", "m")), + Map.entry("items[1]", List.of("l"))); + } + + @Test + void mapKeyWithASquareBracketIsRejected() { + Search search = new Search(); + search.attributes = new LinkedHashMap<>(); + search.attributes.put("size]", "42"); + + assertThatExceptionOfType(EncodeException.class).isThrownBy(() -> encoder.encode(search)) + .withMessageContaining("'size]'") + .withMessageContaining("attributes"); + } + @Test void nullNestedObjectIsSkipped() { Search search = new Search(); @@ -260,6 +301,12 @@ static class Search { Map attributes; + Duration timeout; + + java.util.Currency currency; + + Optional nickname; + } static class Range { From 8eadbe9e7c87127e2e1478a3f93bcd90aae0c2a7 Mon Sep 17 00:00:00 2001 From: Sharang Gupta Date: Fri, 16 Oct 2026 18:57:00 +0100 Subject: [PATCH 4/6] Keep nested objects without properties as is With Spring Data on the classpath, the delegate is the PageableSpringQueryMapEncoder, a BeanQueryMapEncoder that finds no properties in a record, so a nested record was dropped from the query when the option was on, while it is sent as its toString() value without it. Keep a nested object in which the delegate finds no properties as is, as without the option. Signed-off-by: Sharang Gupta --- .../ROOT/pages/spring-cloud-openfeign.adoc | 2 +- .../support/NestedObjectQueryMapEncoder.java | 21 ++++++++---- .../NestedObjectQueryMapEncoderTests.java | 34 +++++++++++++++++++ 3 files changed, 50 insertions(+), 7 deletions(-) diff --git a/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc b/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc index 29d5f0df1..189c6c43e 100644 --- a/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc +++ b/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc @@ -846,7 +846,7 @@ If you need more control over the generated query parameter map, you can impleme By default, a nested object of a `@SpringQueryMap` parameter is sent as the `toString()` value of the object. You can set `spring.cloud.openfeign.client.nested-query-map-enabled` to `true` to send the fields of a nested object as nested query parameters instead, with the property path notation that Spring MVC binds: a nested object as `range.from=1&range.to=2`, the objects of a collection or an array as `filters[0].name=status`, and the entries of a `Map` as `attributes[color]=red`. -Simple values, such as strings, numbers or dates, and the values of the other JDK types, such as an `Optional` or a `Duration`, are sent as before. +Simple values, such as strings, numbers or dates, and the values of the other JDK types, such as an `Optional` or a `Duration`, are sent as before, and so is a nested object in which the delegate `QueryMapEncoder` finds no properties, such as a record for the `PageableSpringQueryMapEncoder`. A collection or an array is indexed only when all its elements are nested objects, so a collection with simple values, such as a `List`, is still sent as repeated query parameters. A `Map` key with a square bracket cannot be written in the property path of its entry, so it is rejected with an `EncodeException`. diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java index 6d1e68c53..0d2ce872c 100644 --- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java @@ -46,11 +46,13 @@ *
  • the entries of a map: {@code attributes[color]=red}
  • * * Simple values and the values of other JDK types, such as an {@code Optional} or a - * {@code Duration}, are kept as is. A collection or an array is encoded with the index of - * its elements only when none of them is such a value, so a collection that has some, - * such as a {@code List}, is still sent as repeated query parameters. A map key - * with a square bracket, and a value that is nested in itself, directly or through other - * values, are rejected with an {@link EncodeException}. + * {@code Duration}, are kept as is, and so is a nested object for which the delegate + * finds no properties, such as a record for a {@code BeanQueryMapEncoder}. A collection + * or an array is encoded with the index of its elements only when none of them is such a + * value, so a collection that has some, such as a {@code List}, is still sent as + * repeated query parameters. A map key with a square bracket, and a value that is nested + * in itself, directly or through other values, are rejected with an + * {@link EncodeException}. * * @author Sharang Gupta * @since 5.1.0 @@ -107,7 +109,14 @@ else if (value instanceof Iterable || value.getClass().isArray()) { addElements(queryMap, name, value, path); } else { - addAll(queryMap, name + ".", delegate.encode(value), path); + Map properties = delegate.encode(value); + if (properties.isEmpty()) { + // The delegate found no properties, such as a BeanQueryMapEncoder for a + // record, so keep the value as it is sent without this encoder + queryMap.put(name, value); + return; + } + addAll(queryMap, name + ".", properties, path); } } diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java index 26ed5181c..00a99f718 100644 --- a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java @@ -261,6 +261,15 @@ void mapReferencedTwiceIsEncodedTwice() { Map.entry("attributes[back][color]", "red")); } + @Test + void nestedObjectWithoutPropertiesForTheDelegateIsKeptAsIs() { + QueryMapEncoder beanEncoder = new NestedObjectQueryMapEncoder(new PageableSpringQueryMapEncoder()); + PricedSearch search = new PricedSearch("shoes", new PriceRange(10, 20)); + + assertThat(beanEncoder.encode(search)).containsOnly(Map.entry("query", "shoes"), + Map.entry("price", search.getPrice())); + } + @Test void worksWithThePageableQueryMapEncoder() { QueryMapEncoder pageableEncoder = new NestedObjectQueryMapEncoder(new PageableSpringQueryMapEncoder()); @@ -358,6 +367,31 @@ static class Holder { } + public static class PricedSearch { + + private final String query; + + private final PriceRange price; + + PricedSearch(String query, PriceRange price) { + this.query = query; + this.price = price; + } + + public String getQuery() { + return this.query; + } + + public PriceRange getPrice() { + return this.price; + } + + } + + record PriceRange(Integer from, Integer to) { + + } + static class Node { Node parent; From cf6a86a0db4c82cd21bc29d8b489519ff26c4f57 Mon Sep 17 00:00:00 2001 From: Sharang Gupta Date: Mon, 19 Oct 2026 20:23:10 +0100 Subject: [PATCH 5/6] Configure nested query maps per client Following the review: - Replace the global spring.cloud.openfeign.client.nested-query-map-enabled property with a client option, spring.cloud.openfeign.client.config..nested-query-map-enabled, which the default configuration can set for every client. A NestedQueryMapCapability decorates the QueryMapEncoder of the client when it is built, so it also applies to a custom encoder, and FeignClientsConfiguration no longer decorates the default one. - Skip a nested object whose properties are all null, like a null value, instead of sending its toString(). Use the components of a record when the delegate finds no properties in it, as the PageableSpringQueryMapEncoder does. - Check the elements of a collection without building a second list. Signed-off-by: Sharang Gupta --- .../ROOT/pages/spring-cloud-openfeign.adoc | 7 +- .../openfeign/FeignClientFactoryBean.java | 8 ++ .../openfeign/FeignClientProperties.java | 44 +++---- .../openfeign/FeignClientsConfiguration.java | 23 +--- .../support/NestedObjectQueryMapEncoder.java | 47 ++++--- .../support/NestedQueryMapCapability.java | 37 ++++++ ...stedQueryMapDefaultConfigurationTests.java | 66 ++++++++++ .../querymap/NestedQueryMapTests.java | 24 +++- ...jectQueryMapEncoderConfigurationTests.java | 119 ------------------ .../NestedObjectQueryMapEncoderTests.java | 23 +++- 10 files changed, 211 insertions(+), 187 deletions(-) create mode 100644 spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedQueryMapCapability.java create mode 100644 spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapDefaultConfigurationTests.java delete mode 100644 spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderConfigurationTests.java diff --git a/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc b/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc index 189c6c43e..a5c32fc4e 100644 --- a/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc +++ b/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc @@ -845,8 +845,9 @@ If you need more control over the generated query parameter map, you can impleme ==== Nested objects By default, a nested object of a `@SpringQueryMap` parameter is sent as the `toString()` value of the object. -You can set `spring.cloud.openfeign.client.nested-query-map-enabled` to `true` to send the fields of a nested object as nested query parameters instead, with the property path notation that Spring MVC binds: a nested object as `range.from=1&range.to=2`, the objects of a collection or an array as `filters[0].name=status`, and the entries of a `Map` as `attributes[color]=red`. -Simple values, such as strings, numbers or dates, and the values of the other JDK types, such as an `Optional` or a `Duration`, are sent as before, and so is a nested object in which the delegate `QueryMapEncoder` finds no properties, such as a record for the `PageableSpringQueryMapEncoder`. +You can set `spring.cloud.openfeign.client.config..nested-query-map-enabled` to `true` to send the fields of a nested object as nested query parameters instead for a client, or `spring.cloud.openfeign.client.config.default.nested-query-map-enabled` for every client, with the property path notation that Spring MVC binds: a nested object as `range.from=1&range.to=2`, the objects of a collection or an array as `filters[0].name=status`, and the entries of a `Map` as `attributes[color]=red`. +Simple values, such as strings, numbers or dates, and the values of the other JDK types, such as an `Optional` or a `Duration`, are sent as before. +A nested object whose properties are all `null` is skipped, like a `null` value. A collection or an array is indexed only when all its elements are nested objects, so a collection with simple values, such as a `List`, is still sent as repeated query parameters. A `Map` key with a square bracket cannot be written in the property path of its entry, so it is rejected with an `EncodeException`. @@ -873,7 +874,7 @@ public class Range { a call to `demoEndpoint(@SpringQueryMap Search search)` sends `query=shoes&price.from=10&price.to=20&filters[0].name=color&filters[0].value=red`, which a Spring MVC handler can bind with `@ModelAttribute Search search`. The option is disabled by default, to keep the behaviour of the existing applications. -When it is enabled, the `QueryMapEncoder` that Spring Cloud OpenFeign auto-configures is decorated with the `NestedObjectQueryMapEncoder`, which you can also use to decorate a custom `QueryMapEncoder` bean. +When it is enabled for a client, the `QueryMapEncoder` of the client, whether it is the auto-configured one or a custom one, is decorated with the `NestedObjectQueryMapEncoder`. [[hateoas-support]] === HATEOAS support diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java index 1e68acc3b..6c711f4bc 100644 --- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java @@ -56,6 +56,7 @@ import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer; import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient; import org.springframework.cloud.openfeign.loadbalancer.RetryableFeignBlockingLoadBalancerClient; +import org.springframework.cloud.openfeign.support.NestedQueryMapCapability; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.annotation.AnnotationAwareOrderComparator; @@ -78,6 +79,7 @@ * @author Felix Dittrich * @author Dominique Villard * @author Can Bezmen + * @author Sharang Gupta */ public class FeignClientFactoryBean implements FactoryBean, InitializingBean, ApplicationContextAware, BeanFactoryAware { @@ -275,6 +277,12 @@ protected void configureUsingProperties(FeignClientProperties.FeignClientConfigu builder.dismiss404(); } } + Boolean nestedQueryMapEnabled = finalConfig != null && finalConfig.getNestedQueryMapEnabled() != null + ? finalConfig.getNestedQueryMapEnabled() + : (baseConfig != null ? baseConfig.getNestedQueryMapEnabled() : null); + if (Boolean.TRUE.equals(nestedQueryMapEnabled)) { + builder.addCapability(new NestedQueryMapCapability()); + } } protected void configureUsingProperties(FeignClientProperties.FeignClientConfiguration config, diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java index 4cde2f45e..7feb5c6a6 100644 --- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java @@ -67,14 +67,6 @@ public class FeignClientProperties { */ private boolean removeTrailingSlash; - /** - * If {@code true}, the nested objects of a {@code @SpringQueryMap} parameter are sent - * as nested query parameters (for example, {@code range.from=1&range.to=2}) instead - * of their {@code toString()} value, and the objects of a collection or an array as - * indexed query parameters (for example, {@code filters[0].name=status}). - */ - private boolean nestedQueryMapEnabled; - public boolean isDefaultToProperties() { return defaultToProperties; } @@ -115,14 +107,6 @@ public void setRemoveTrailingSlash(boolean removeTrailingSlash) { this.removeTrailingSlash = removeTrailingSlash; } - public boolean isNestedQueryMapEnabled() { - return nestedQueryMapEnabled; - } - - public void setNestedQueryMapEnabled(boolean nestedQueryMapEnabled) { - this.nestedQueryMapEnabled = nestedQueryMapEnabled; - } - @Override public boolean equals(Object o) { if (this == o) { @@ -134,14 +118,12 @@ public boolean equals(Object o) { FeignClientProperties that = (FeignClientProperties) o; return defaultToProperties == that.defaultToProperties && Objects.equals(defaultConfig, that.defaultConfig) && Objects.equals(config, that.config) && Objects.equals(decodeSlash, that.decodeSlash) - && Objects.equals(removeTrailingSlash, that.removeTrailingSlash) - && nestedQueryMapEnabled == that.nestedQueryMapEnabled; + && Objects.equals(removeTrailingSlash, that.removeTrailingSlash); } @Override public int hashCode() { - return Objects.hash(defaultToProperties, defaultConfig, config, decodeSlash, removeTrailingSlash, - nestedQueryMapEnabled); + return Objects.hash(defaultToProperties, defaultConfig, config, decodeSlash, removeTrailingSlash); } /** @@ -181,6 +163,15 @@ public static class FeignClientConfiguration { private Class queryMapEncoder; + /** + * If {@code true}, the nested objects of a {@code @SpringQueryMap} parameter are + * sent as nested query parameters (for example, {@code range.from=1&range.to=2}) + * instead of their {@code toString()} value, and the objects of a collection or + * an array as indexed query parameters (for example, + * {@code filters[0].name=status}). + */ + private Boolean nestedQueryMapEnabled; + private MicrometerProperties micrometer; private Boolean followRedirects; @@ -319,6 +310,14 @@ public void setQueryMapEncoder(Class queryMapEncoder) { this.queryMapEncoder = queryMapEncoder; } + public Boolean getNestedQueryMapEnabled() { + return nestedQueryMapEnabled; + } + + public void setNestedQueryMapEnabled(Boolean nestedQueryMapEnabled) { + this.nestedQueryMapEnabled = nestedQueryMapEnabled; + } + public MicrometerProperties getMicrometer() { return micrometer; } @@ -364,6 +363,7 @@ public boolean equals(Object o) { && Objects.equals(defaultQueryParameters, that.defaultQueryParameters) && Objects.equals(capabilities, that.capabilities) && Objects.equals(queryMapEncoder, that.queryMapEncoder) + && Objects.equals(nestedQueryMapEnabled, that.nestedQueryMapEnabled) && Objects.equals(micrometer, that.micrometer) && Objects.equals(followRedirects, that.followRedirects) && Objects.equals(url, that.url); } @@ -372,8 +372,8 @@ public boolean equals(Object o) { public int hashCode() { return Objects.hash(loggerLevel, connectTimeout, readTimeout, retryer, errorDecoder, requestInterceptors, responseInterceptor, dismiss404, encoder, decoder, contract, exceptionPropagationPolicy, - defaultQueryParameters, defaultRequestHeaders, capabilities, queryMapEncoder, micrometer, - followRedirects, url); + defaultQueryParameters, defaultRequestHeaders, capabilities, queryMapEncoder, nestedQueryMapEnabled, + micrometer, followRedirects, url); } } diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java index b8790fc44..97916b844 100644 --- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java @@ -52,7 +52,6 @@ import org.springframework.cloud.openfeign.support.FeignEncoderProperties; import org.springframework.cloud.openfeign.support.FeignHttpMessageConverters; import org.springframework.cloud.openfeign.support.HttpMessageConverterCustomizer; -import org.springframework.cloud.openfeign.support.NestedObjectQueryMapEncoder; import org.springframework.cloud.openfeign.support.PageableSpringEncoder; import org.springframework.cloud.openfeign.support.PageableSpringQueryMapEncoder; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; @@ -80,7 +79,6 @@ * @author Olga Maciaszek-Sharma * @author Hyeonmin Park * @author Yanming Zhou - * @author Sharang Gupta */ @Configuration(proxyBeanMethods = false) public class FeignClientsConfiguration { @@ -129,7 +127,7 @@ public Encoder feignEncoder(ObjectProvider formWriterProvide @ConditionalOnMissingBean @ConditionalOnMissingClass("org.springframework.data.domain.Pageable") public QueryMapEncoder feignQueryMapEncoder() { - return withNestedObjectSupport(new SpringFieldQueryMapEncoder(), feignClientProperties); + return new SpringFieldQueryMapEncoder(); } @Bean @@ -180,20 +178,6 @@ private static Encoder springEncoder(ObjectProvider formWrit } } - /** - * Decorate the query map encoder with the {@link NestedObjectQueryMapEncoder} when - * the {@code spring.cloud.openfeign.client.nested-query-map-enabled} property is set. - * @param queryMapEncoder the query map encoder of the auto-configuration. - * @param properties the Feign client properties, if any. - * @return the query map encoder to use. - */ - static QueryMapEncoder withNestedObjectSupport(QueryMapEncoder queryMapEncoder, FeignClientProperties properties) { - if (properties != null && properties.isNestedQueryMapEnabled()) { - return new NestedObjectQueryMapEncoder(queryMapEncoder); - } - return queryMapEncoder; - } - private static class SpringPojoFormEncoder extends SpringFormEncoder { SpringPojoFormEncoder(AbstractFormWriter formWriter) { @@ -209,9 +193,6 @@ private static class SpringPojoFormEncoder extends SpringFormEncoder { @ConditionalOnClass({ Pageable.class, DataWebProperties.class }) static class SpringDataConfiguration { - @Autowired(required = false) - private FeignClientProperties feignClientProperties; - private final DataWebProperties dataWebProperties; SpringDataConfiguration(ObjectProvider dataWebProperties) { @@ -243,7 +224,7 @@ public QueryMapEncoder feignQueryMapEncoderPageable() { queryMapEncoder.setSizeParameter(dataWebProperties.getPageable().getSizeParameter()); queryMapEncoder.setSortParameter(dataWebProperties.getSort().getSortParameter()); } - return withNestedObjectSupport(queryMapEncoder, feignClientProperties); + return queryMapEncoder; } } diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java index 0d2ce872c..d6316ba7a 100644 --- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java @@ -17,6 +17,8 @@ package org.springframework.cloud.openfeign.support; import java.lang.reflect.Array; +import java.lang.reflect.Method; +import java.lang.reflect.RecordComponent; import java.util.ArrayList; import java.util.Collections; import java.util.IdentityHashMap; @@ -31,6 +33,7 @@ import org.springframework.beans.BeanUtils; import org.springframework.util.Assert; +import org.springframework.util.ReflectionUtils; /** * A {@link QueryMapEncoder} that sends the nested objects of a query map parameter as @@ -46,17 +49,18 @@ *
  • the entries of a map: {@code attributes[color]=red}
  • * * Simple values and the values of other JDK types, such as an {@code Optional} or a - * {@code Duration}, are kept as is, and so is a nested object for which the delegate - * finds no properties, such as a record for a {@code BeanQueryMapEncoder}. A collection - * or an array is encoded with the index of its elements only when none of them is such a - * value, so a collection that has some, such as a {@code List}, is still sent as - * repeated query parameters. A map key with a square bracket, and a value that is nested - * in itself, directly or through other values, are rejected with an - * {@link EncodeException}. + * {@code Duration}, are kept as is. A nested object whose properties are all {@code null} + * is skipped, like a {@code null} value. The components of a record are used when the + * delegate finds no properties in it, as a {@code BeanQueryMapEncoder} does, such as the + * one for Spring Data. A collection or an array is encoded with the index of its elements + * only when none of them is such a value, so a collection that has some, such as a + * {@code List}, is still sent as repeated query parameters. A map key with a + * square bracket, and a value that is nested in itself, directly or through other values, + * are rejected with an {@link EncodeException}. * * @author Sharang Gupta * @since 5.1.0 - * @see org.springframework.cloud.openfeign.FeignClientProperties#isNestedQueryMapEnabled() + * @see org.springframework.cloud.openfeign.FeignClientProperties.FeignClientConfiguration#getNestedQueryMapEnabled() */ public class NestedObjectQueryMapEncoder implements QueryMapEncoder { @@ -110,12 +114,11 @@ else if (value instanceof Iterable || value.getClass().isArray()) { } else { Map properties = delegate.encode(value); - if (properties.isEmpty()) { - // The delegate found no properties, such as a BeanQueryMapEncoder for a - // record, so keep the value as it is sent without this encoder - queryMap.put(name, value); - return; + if (properties.isEmpty() && value instanceof Record record) { + // A BeanQueryMapEncoder finds no properties in a record + properties = componentsOf(record); } + // An object whose properties are all null adds nothing, like a null value addAll(queryMap, name + ".", properties, path); } } @@ -143,9 +146,21 @@ private static String mapKey(String name, Object key) { } private static boolean areAllNested(List elements) { - List presentElements = elements.stream().filter(Objects::nonNull).toList(); - return !presentElements.isEmpty() - && presentElements.stream().noneMatch(NestedObjectQueryMapEncoder::isPlainValue); + return elements.stream().anyMatch(Objects::nonNull) + && elements.stream().noneMatch(element -> element != null && isPlainValue(element)); + } + + private static Map componentsOf(Record record) { + Map components = new LinkedHashMap<>(); + for (RecordComponent component : record.getClass().getRecordComponents()) { + Method accessor = component.getAccessor(); + ReflectionUtils.makeAccessible(accessor); + Object componentValue = ReflectionUtils.invokeMethod(accessor, record); + if (componentValue != null) { + components.put(component.getName(), componentValue); + } + } + return components; } private static boolean isPlainValue(Object value) { diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedQueryMapCapability.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedQueryMapCapability.java new file mode 100644 index 000000000..2371e96c0 --- /dev/null +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedQueryMapCapability.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.openfeign.support; + +import feign.Capability; +import feign.QueryMapEncoder; + +/** + * A {@link Capability} that decorates the {@link QueryMapEncoder} of a Feign client, + * whichever it is, with the {@link NestedObjectQueryMapEncoder}. + * + * @author Sharang Gupta + * @since 5.1.0 + * @see org.springframework.cloud.openfeign.FeignClientProperties.FeignClientConfiguration#getNestedQueryMapEnabled() + */ +public class NestedQueryMapCapability implements Capability { + + @Override + public QueryMapEncoder enrich(QueryMapEncoder queryMapEncoder) { + return new NestedObjectQueryMapEncoder(queryMapEncoder); + } + +} diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapDefaultConfigurationTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapDefaultConfigurationTests.java new file mode 100644 index 000000000..1d2dce2f1 --- /dev/null +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapDefaultConfigurationTests.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.openfeign.querymap; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.openfeign.querymap.NestedQueryMapTests.PlainSearchClient; +import org.springframework.cloud.openfeign.querymap.NestedQueryMapTests.SearchClient; +import org.springframework.test.annotation.DirtiesContext; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +/** + * Tests for the {@code nested-query-map-enabled} option in the default configuration of + * the Feign clients, overridden by the configuration of a client. + * + * @author Sharang Gupta + */ +@SpringBootTest(classes = NestedQueryMapTests.Application.class, webEnvironment = RANDOM_PORT, + value = { "spring.application.name=nestedquerymaptest", "spring.jmx.enabled=false", + "spring.cloud.openfeign.client.config.default.nested-query-map-enabled=true", + "spring.cloud.openfeign.client.config.plainSearch.nested-query-map-enabled=false" }) +@DirtiesContext +class NestedQueryMapDefaultConfigurationTests { + + @Autowired + private SearchClient searchClient; + + @Autowired + private PlainSearchClient plainSearchClient; + + @Test + void defaultConfigurationEnablesTheOptionForEveryClient() { + Map> parameters = this.searchClient.parameters(NestedQueryMapTests.search()); + + assertThat(parameters).containsKeys("price.from", "price.to"); + } + + @Test + void configurationOfAClientOverridesTheDefaultConfiguration() { + Map> parameters = this.plainSearchClient.parameters(NestedQueryMapTests.search()); + + assertThat(parameters).containsKey("price").doesNotContainKey("price.from"); + } + +} diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapTests.java index e67c51a45..011bd767c 100644 --- a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/querymap/NestedQueryMapTests.java @@ -55,13 +55,16 @@ */ @SpringBootTest(classes = NestedQueryMapTests.Application.class, webEnvironment = RANDOM_PORT, value = { "spring.application.name=nestedquerymaptest", "spring.jmx.enabled=false", - "spring.cloud.openfeign.client.nested-query-map-enabled=true" }) + "spring.cloud.openfeign.client.config.local.nested-query-map-enabled=true" }) @DirtiesContext class NestedQueryMapTests { @Autowired private SearchClient searchClient; + @Autowired + private PlainSearchClient plainSearchClient; + @Test void nestedObjectsAreSentAsNestedQueryParameters() { Map> parameters = this.searchClient.parameters(search()); @@ -88,7 +91,14 @@ void nestedQueryParametersAreBoundByTheServer() { assertThat(bound.getGroups()).containsExactly(List.of("s", "m"), List.of("l")); } - private static SearchRequest search() { + @Test + void clientWithoutTheOptionSendsNestedObjectsAsBefore() { + Map> parameters = this.plainSearchClient.parameters(search()); + + assertThat(parameters).containsKey("price").doesNotContainKey("price.from"); + } + + static SearchRequest search() { SearchRequest request = new SearchRequest(); request.setQuery("shoes"); request.setPrice(new Range(10, 20)); @@ -126,7 +136,15 @@ SearchRequest echo(@ModelAttribute SearchRequest request) { } - @EnableFeignClients(clients = SearchClient.class) + @FeignClient(name = "local", contextId = "plainSearch") + interface PlainSearchClient { + + @GetMapping("/search/parameters") + Map> parameters(@SpringQueryMap SearchRequest request); + + } + + @EnableFeignClients(clients = { SearchClient.class, PlainSearchClient.class }) @LoadBalancerClient(name = "local", configuration = LocalClientConfiguration.class) @SpringBootApplication @Import({ NoSecurityConfiguration.class, SearchController.class }) diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderConfigurationTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderConfigurationTests.java deleted file mode 100644 index fd66173f6..000000000 --- a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderConfigurationTests.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2013-present the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.openfeign.support; - -import java.util.Map; - -import feign.QueryMapEncoder; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.openfeign.FeignClientFactory; -import org.springframework.test.annotation.DirtiesContext; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * Tests for the {@code spring.cloud.openfeign.client.nested-query-map-enabled} property. - * - * @author Sharang Gupta - */ -class NestedObjectQueryMapEncoderConfigurationTests { - - @Nested - @SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = RANDOM_PORT, - value = { "spring.application.name=nestedquerymaptest", "spring.jmx.enabled=false", - "spring.cloud.openfeign.client.nested-query-map-enabled=true" }) - @DirtiesContext - class WhenEnabled { - - @Autowired - private FeignClientFactory context; - - @Test - void queryMapEncoderSendsNestedObjectsAsNestedQueryParameters() { - QueryMapEncoder encoder = this.context.getInstance("foo", QueryMapEncoder.class); - - assertThat(encoder).isInstanceOf(NestedObjectQueryMapEncoder.class); - assertThat(encoder.encode(new Search(new Range(1, 2)))).containsOnly(Map.entry("price.from", 1), - Map.entry("price.to", 2)); - } - - } - - @Nested - @SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = RANDOM_PORT, - value = { "spring.application.name=nestedquerymaptest", "spring.jmx.enabled=false" }) - @DirtiesContext - class WhenDisabled { - - @Autowired - private FeignClientFactory context; - - @Test - void queryMapEncoderIsUnchangedByDefault() { - QueryMapEncoder encoder = this.context.getInstance("foo", QueryMapEncoder.class); - - assertThat(encoder).isNotInstanceOf(NestedObjectQueryMapEncoder.class); - assertThat(encoder.encode(new Search(new Range(1, 2)))).containsOnlyKeys("price"); - } - - } - - /** - * The Spring Data query map encoder invokes the getters reflectively, so the classes - * must be public. - */ - public static class Search { - - private final Range price; - - Search(Range price) { - this.price = price; - } - - public Range getPrice() { - return price; - } - - } - - public static class Range { - - private final Integer from; - - private final Integer to; - - Range(Integer from, Integer to) { - this.from = from; - this.to = to; - } - - public Integer getFrom() { - return from; - } - - public Integer getTo() { - return to; - } - - } - -} diff --git a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java index 00a99f718..af6480494 100644 --- a/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java +++ b/spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoderTests.java @@ -262,12 +262,29 @@ void mapReferencedTwiceIsEncodedTwice() { } @Test - void nestedObjectWithoutPropertiesForTheDelegateIsKeptAsIs() { + void nestedRecordIsEncodedWithItsComponentsWhenTheDelegateFindsNoProperties() { QueryMapEncoder beanEncoder = new NestedObjectQueryMapEncoder(new PageableSpringQueryMapEncoder()); PricedSearch search = new PricedSearch("shoes", new PriceRange(10, 20)); - assertThat(beanEncoder.encode(search)).containsOnly(Map.entry("query", "shoes"), - Map.entry("price", search.getPrice())); + assertThat(beanEncoder.encode(search)).containsOnly(Map.entry("query", "shoes"), Map.entry("price.from", 10), + Map.entry("price.to", 20)); + } + + @Test + void nestedRecordWithOnlyNullComponentsIsSkipped() { + QueryMapEncoder beanEncoder = new NestedObjectQueryMapEncoder(new PageableSpringQueryMapEncoder()); + + assertThat(beanEncoder.encode(new PricedSearch("shoes", new PriceRange(null, null)))) + .containsOnly(Map.entry("query", "shoes")); + } + + @Test + void nestedObjectWithOnlyNullPropertiesIsSkipped() { + Search search = new Search(); + search.query = "shoes"; + search.price = new Range(null, null); + + assertThat(encoder.encode(search)).containsOnly(Map.entry("query", "shoes")); } @Test From d003160d07b7c3f76195fbc5811c1230bbfbdd28 Mon Sep 17 00:00:00 2001 From: Sharang Gupta Date: Mon, 19 Oct 2026 21:17:19 +0100 Subject: [PATCH 6/6] Log skipped objects and iterate the elements Following the review: - Log at debug level when a nested object is skipped because none of its properties has a value. - Iterate the elements of an Iterable, or of the List of an array, instead of copying them into another list. - Split the long sentence of the docs, and note that, like the other client configuration properties, the option has no effect on a client that does not inherit the parent configuration. Signed-off-by: Sharang Gupta --- .../ROOT/pages/spring-cloud-openfeign.adoc | 10 +++- .../support/NestedObjectQueryMapEncoder.java | 56 ++++++++++--------- 2 files changed, 39 insertions(+), 27 deletions(-) diff --git a/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc b/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc index a5c32fc4e..ab0f0cdfc 100644 --- a/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc +++ b/docs/modules/ROOT/pages/spring-cloud-openfeign.adoc @@ -845,7 +845,13 @@ If you need more control over the generated query parameter map, you can impleme ==== Nested objects By default, a nested object of a `@SpringQueryMap` parameter is sent as the `toString()` value of the object. -You can set `spring.cloud.openfeign.client.config..nested-query-map-enabled` to `true` to send the fields of a nested object as nested query parameters instead for a client, or `spring.cloud.openfeign.client.config.default.nested-query-map-enabled` for every client, with the property path notation that Spring MVC binds: a nested object as `range.from=1&range.to=2`, the objects of a collection or an array as `filters[0].name=status`, and the entries of a `Map` as `attributes[color]=red`. +To send the fields of nested objects as nested query parameters instead, set `spring.cloud.openfeign.client.config..nested-query-map-enabled` to `true` for a client, or `spring.cloud.openfeign.client.config.default.nested-query-map-enabled` for every client. +The query parameters then use the property path notation that Spring MVC binds: + +* a nested object is sent as `range.from=1&range.to=2` +* the objects of a collection or an array are sent as `filters[0].name=status` +* the entries of a `Map` are sent as `attributes[color]=red` + Simple values, such as strings, numbers or dates, and the values of the other JDK types, such as an `Optional` or a `Duration`, are sent as before. A nested object whose properties are all `null` is skipped, like a `null` value. A collection or an array is indexed only when all its elements are nested objects, so a collection with simple values, such as a `List`, is still sent as repeated query parameters. @@ -876,6 +882,8 @@ a call to `demoEndpoint(@SpringQueryMap Search search)` sends `query=shoes&price The option is disabled by default, to keep the behaviour of the existing applications. When it is enabled for a client, the `QueryMapEncoder` of the client, whether it is the auto-configured one or a custom one, is decorated with the `NestedObjectQueryMapEncoder`. +NOTE: Like the other `spring.cloud.openfeign.client.config.*` properties, `nested-query-map-enabled` has no effect on a client whose `FeignClientConfigurer` returns `false` from `inheritParentConfiguration()` (see <>). + [[hateoas-support]] === HATEOAS support diff --git a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java index d6316ba7a..a03e7f2d6 100644 --- a/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java +++ b/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/NestedObjectQueryMapEncoder.java @@ -16,23 +16,22 @@ package org.springframework.cloud.openfeign.support; -import java.lang.reflect.Array; import java.lang.reflect.Method; import java.lang.reflect.RecordComponent; -import java.util.ArrayList; import java.util.Collections; import java.util.IdentityHashMap; import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; import feign.QueryMapEncoder; import feign.codec.EncodeException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanUtils; import org.springframework.util.Assert; +import org.springframework.util.CollectionUtils; import org.springframework.util.ReflectionUtils; /** @@ -64,6 +63,8 @@ */ public class NestedObjectQueryMapEncoder implements QueryMapEncoder { + private static final Log LOG = LogFactory.getLog(NestedObjectQueryMapEncoder.class); + private final QueryMapEncoder delegate; public NestedObjectQueryMapEncoder(QueryMapEncoder delegate) { @@ -118,21 +119,29 @@ else if (value instanceof Iterable || value.getClass().isArray()) { // A BeanQueryMapEncoder finds no properties in a record properties = componentsOf(record); } - // An object whose properties are all null adds nothing, like a null value + if (properties.isEmpty()) { + // An object whose properties are all null adds nothing, like a null value + if (LOG.isDebugEnabled()) { + LOG.debug("Skipping the nested object '" + name + "' of type " + value.getClass().getName() + + " from the query map, as none of its properties has a value"); + } + return; + } addAll(queryMap, name + ".", properties, path); } } private void addElements(Map queryMap, String name, Object value, Set path) { - List elements = toList(value); + Iterable elements = (value instanceof Iterable iterable) ? iterable : CollectionUtils.arrayToList(value); if (!areAllNested(elements)) { // A plain value has no property path to index, so keep the elements as Feign // sends them: an Iterable as repeated query parameters - queryMap.put(name, value instanceof Iterable ? value : elements); + queryMap.put(name, elements); return; } - for (int index = 0; index < elements.size(); index++) { - add(queryMap, name + "[" + index + "]", elements.get(index), path); + int index = 0; + for (Object element : elements) { + add(queryMap, name + "[" + index++ + "]", element, path); } } @@ -145,9 +154,18 @@ private static String mapKey(String name, Object key) { return mapKey; } - private static boolean areAllNested(List elements) { - return elements.stream().anyMatch(Objects::nonNull) - && elements.stream().noneMatch(element -> element != null && isPlainValue(element)); + private static boolean areAllNested(Iterable elements) { + boolean anyPresent = false; + for (Object element : elements) { + if (element == null) { + continue; + } + if (isPlainValue(element)) { + return false; + } + anyPresent = true; + } + return anyPresent; } private static Map componentsOf(Record record) { @@ -172,18 +190,4 @@ private static boolean isPlainValue(Object value) { || typeName.startsWith("javax."); } - private static List toList(Object value) { - List elements = new ArrayList<>(); - if (value instanceof Iterable iterable) { - iterable.forEach(elements::add); - } - else { - int length = Array.getLength(value); - for (int index = 0; index < length; index++) { - elements.add(Array.get(value, index)); - } - } - return elements; - } - }