diff --git a/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java b/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java index a53902dd84..71479a8cb8 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java @@ -16,6 +16,7 @@ package org.springframework.boot.web.client; +import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; @@ -317,7 +318,19 @@ public class RestTemplateBuilder { public RestTemplateBuilder requestFactory( Class requestFactory) { Assert.notNull(requestFactory, "RequestFactory must not be null"); - return requestFactory(BeanUtils.instantiate(requestFactory)); + return requestFactory(createRequestFactory(requestFactory)); + } + + private ClientHttpRequestFactory createRequestFactory( + Class requestFactory) { + try { + Constructor constructor = requestFactory.getDeclaredConstructor(); + constructor.setAccessible(true); + return (ClientHttpRequestFactory) constructor.newInstance(); + } + catch (Exception ex) { + throw new IllegalStateException(ex); + } } /** diff --git a/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java b/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java index 6cabe7810a..087eef172c 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java @@ -278,6 +278,14 @@ public class RestTemplateBuilderTests { .isInstanceOf(SimpleClientHttpRequestFactory.class); } + @Test + public void requestFactoryPackagePrivateClassShouldApply() throws Exception { + RestTemplate template = this.builder + .requestFactory(TestClientHttpRequestFactory.class).build(); + assertThat(template.getRequestFactory()) + .isInstanceOf(TestClientHttpRequestFactory.class); + } + @Test public void requestFactoryWhenFactoryIsNullShouldThrowException() throws Exception { this.thrown.expect(IllegalArgumentException.class); @@ -547,4 +555,8 @@ public class RestTemplateBuilderTests { } + static class TestClientHttpRequestFactory extends SimpleClientHttpRequestFactory { + + } + }