I was using a previous version of Spring Boot and creating a RestTemplate using RestTemplateBuilder. Since 2.2.6 I get NPE because I was not setting any of defaultHeaders or requestCustomizers and they are "null" by default.

So when this.[null variable].isEmpty() is performed you get NPE.

For requestCustomizers I can use

builder.requestCustomizers(Collections.emptyList())

to avoid the NPE

But what should I use to set defaultHeaders to empty collection? There is no method to allow that. If I set

builder.defaultHeader(null,null)

I get validation error as "null" is not allowed.

I could use

builder.defaultHeader("","") which will solve the NPE (it initialises defaultHeaders to empty map an adds this header) but I would like to avoid unnecessary headers.

Here is the check: https://github.com/spring-projects/spring-boot/blob/ad326036353112e938166b5b59dcaf643e949c1d/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java#L662

Comment From: philwebb

I'm not sure how those values are ending up as null. Looking at the code, I would expect them to be empty collections.

@razvan100 Do you have a sample application you can share that shows the exception?

Comment From: razvan100

Hi @philwebb, thank you for such fast reply.

I can post how I initialised the RestTemplate before (spring-boot 2.1.2.RELEASE)

@Bean
@Autowired
public RestTemplate restTemplate(MyConfiguration configuration,
                                 Supplier<ClientHttpRequestFactory> requestFactorySupplier,
                                 LoggingRequestInterceptor loggingRequestInterceptor,
                                 ErrorHandler errorHandler, RestTemplateBuilder builder) {
    return builder
            .requestFactory(requestFactorySupplier)
            .rootUri(configuration.getBaseUrl())
            .additionalInterceptors(loggingRequestInterceptor)
            .errorHandler(errorHandler)
            .build();
}

I wanted to upgrade my application to use 2.2.6.RELEASE and with the same code I get the NPE because this method is called this.addClientHttpRequestInitializer(restTemplate); in the link I posted.

Comment From: razvan100

I'm sorry about this, I wasn't paying enough attention to the code. The builder is mocked (with Mockito) in the test I was running therefore all it's member variables are null. It's only the test that fails not the RestTemplateBuilder itself. My apologies.

Comment From: philwebb

Thanks, that explains it. I don't think we should change the design of RestTemplateBuilder to deal with that so I think you'll need to keep your workarounds.