The Problem:
An error occurs while disabling micrometer tracing in a Spring Boot application. When management.tracing.enabled
is set to false
, the application fails to start with a Bean not found
exception. A workaround is implemented by creating a @Bean
in the configuration, but subsequent requests fail with a Context does not have an entry
error.
The Solutions:
Solution 1: Use ObjectProvider
Instead of directly injecting Tracer
bean, use ObjectProvider
to handle the optional availability of the Tracer
bean. The following code snippet demonstrates how to use ObjectProvider
:
“`java
private final ObjectProvider
// …
public void doSomeJob() {
…
Tracer tracer = tracerProvider.getIfAvailable();
if (tracer != null) {
var context = Optional.ofNullable(tracer.currentTraceContext().context());
// Use the Tracer to get trace and span IDs
} else {
// Handle the case when the Tracer bean is not available
}
…
}
Solution 2: Disabling tracing registry
When you disable tracing, it’s necessary to disable both the Tracer
and ObservationRegistry
beans. In this case, a NoopTracingConfig
class is created to provide these beans when tracing is disabled.
@ConditionalOnProperty(prefix = "management.tracing", name = "enabled", havingValue = "false")
@Configuration
public class NoopTracingConfig {
@Bean
Tracer tracer() {
return Tracer.NOOP;
}
@Bean
ObservationRegistry observationRegistry() {
return ObservationRegistry.NOOP;
}
}
Q&A
What do I do wrong if the application mandates a Tracer bean to be created?
You can use ObjectProvider instead of Tracer.
What should be done when defining NOOP Tracer bean?
Define also NOOP ObservationRegistry bean.
Video Explanation:
The following video, titled "Require single bean but 2 were found in Spring Boot project ...", provides additional insights and in-depth exploration related to the topics discussed in this post.
Consider defining a bean of type in your configuration Field required a bean that could not be found ... Eclipse/SpringBoot bug fixed- application ...
The following video, titled "Require single bean but 2 were found in Spring Boot project ...", provides additional insights and in-depth exploration related to the topics discussed in this post.
Consider defining a bean of type in your configuration Field required a bean that could not be found ... Eclipse/SpringBoot bug fixed- application ...