The @Bean method for ObservationRestTemplateCustomizer (in RestTemplateObservationConfiguration accepts two optional custom beans ( ObjectProvider<ClientRequestObservationConvention> and ObjectProvider<RestTemplateExchangeProvider>)

The method decides internally, whether one of the custom Beans should be used (if available) or to use a DefaultClientRequestObservationConvention .

The problem is (as far as I understand ;-), that ObjectProvider.getIfAvailable() returns null, if a matching bean definition exists but the bean singleton hasn't allready been instantiated.

In our concrete case, we do provide a custom autoconfiguration providing a custom ClientRequestObservationConvention Bean. This bean is ignored during the creation of ObservationRestTemplateCustomizer .

Even `@AutoconfigureBefore(HttpClientObservationsAutoConfiguration.class) does not help - (obviously because @AutoconfigureBefore/After controls the order of bean definition, not the order of bean creation )

Putting the @Bean ClientRequestObservationConvention in the regular SpringBootApplication Configuration is a workaround that works in our tests. But I am not sure whether this behavior is deterministic and we need a solution, that works with autoconfigurations too.

I think, changing the parameter type from ObjectProvider<ClientRequestObservationConvention> to Optional<ClientRequestObserverationConvention> could solve the problem, because now, a possibly exsting bean definition will be instantiated before invocation of the @Bean method for ObservationRestTemplateCustomizer ?

Comment From: bclozel

Could you share a sample project with a simplified version of your auto-configuration? I might be missing something, but contributing a bean method in an auto-configuration, as long as ordering is done well, should contribute the bean and make it available to the injection point. We're using this pattern in numerous places in Spring Boot without involving Optional at all.

Comment From: tvahrst

Sorry, just did some further tests and detected my own fault. I annotated my custom bean with a ConditionalOnBean(ObservationRegistry) and did not consider the order of the autoconfigurations. So my custom Bean has not been defined, and this was the reason for missing Usage in the RestTemplateCustomizer.

Comment From: bclozel

I'm glad you found the problem. Thanks for letting us know!