Trying to @Autowired a RestTemplate in Spring Boot 2.1.4 using RestTemplateBuilder. When i run junit tests i get an error when trying to autowired RestTemplate.
I saw here: How to autowire RestTemplate using annotations It seems that RestTemplateBuilder is better so i would like to use that.
This is the configuration file :
@Configuration public class Beans { @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
This is the test class:
@RunWith(SpringRunner.class) @SpringBootTest @ContextConfiguration(classes = Beans.class) public class AppTest extends TestCase { @Autowired private RestTemplate restTemplate; }
The error is :
APPLICATION FAILED TO START *************************** Description: Parameter 0 of method restTemplate in beanDeclerations.Beans required a bean of type 'org.springframework.boot.web.client.RestTemplateBuilder' that could not be found. The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true) Action: Consider defining a bean of type 'org.springframework.boot.web.client.RestTemplateBuilder' in your configuration.
I edited out other autowired that work. What am i missing here? After searching the web i found out that spring auto wired RestTemplateBuilder, why isn’t doing so here?
EDIT: I ended up using @RestClientTest() and had to move RestTemplateBuilder Bean to the main class for now, I’ll move it later to a different place. Thanks for the help.
Advertisement
Answer
The RestTemplateBuilder should be available through an autocofiguration (see: https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfiguration.java). I think this config is missing because of your @ContextConfiguration. You have some possibilities. Try to add the AutoConfig for the RestTemplateBuilder to your ContextConfiguration. Second one is to make a TestConfiguration and create your own RestTemplateBuilder or directly a RestTemplate. The third one is don’t inject the RestTemplate – build it by hand in your test. You can also remove the @ContextConfiguration-Annotation but this will result in a test which loads every config you have defined in your project.
There’s also a RestTestTemplate (https://www.baeldung.com/spring-boot-testresttemplate) which is designed for tests.
@RunWith(SpringRunner.class) @SpringBootTest @ContextConfiguration(classes = {TestConfig.class, RestTemplateAutoConfiguration.class}) public class SandboxApplicationTests { @Autowired RestTemplate restTemplate; @Test public void contextLoads() { } }
The snippet above works for me. Without the RestTemplateAutoConfiguration in the ContextConfiguration the RestTemplate can’t be created because of the missing RestTemplateBuilder-Bean