spring boot version: 2.6.4

After setting spring.main.lazy-initialization=true, hikari related metric disappeared from metric list. Although HikariDataSource is created during application context initialization, it was confirmed that HikariDataSourceMetricsConfiguration is not set. I have confirmed that HikariDataSourceMetricsConfiguration is the target of autoconfiguration as follows.

   DataSourcePoolMetadataProvidersConfiguration.HikariPoolDataSourceMetadataProviderConfiguration matched:
      - @ConditionalOnClass found required class 'com.zaxxer.hikari.HikariDataSource' (OnClassCondition)

   DataSourcePoolMetricsAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'javax.sql.DataSource', 'io.micrometer.core.instrument.MeterRegistry' (OnClassCondition)
      - @ConditionalOnBean (types: javax.sql.DataSource,io.micrometer.core.instrument.MeterRegistry; SearchStrategy: all) found beans 'prometheusMeterRegistry', 'dataSource' (OnBeanCondition)

Comment From: wilkinsona

Thanks for the report. I think this affects all DataSource metrics, not just when using Hikari. You can work around the Hikari metrics problem with the following exclude filter:

@Bean
static LazyInitializationExcludeFilter hikariMetricsLazyInitializationExcludeFilter() {
    return (name, definition, type) -> name.equals(
        "org.springframework.boot.actuate.autoconfigure.metrics.jdbc.DataSourcePoolMetricsAutoConfiguration$HikariDataSourceMetricsConfiguration");
}

Comment From: wilkinsona

DataSource metrics are currently bound via some slightly unusual @Autowired methods and it's been that way since the code was introduced.

If MeterBinder implementations were used instead, I think this would work correctly with lazy initialization. Perhaps there's a reason why a MeterBinder couldn't be used? EachMeterBinder is called as part of post-processing of the MeterRegistry bean which is earlier than the @Autowired approach which will happen sometime after the registry has been fully initialized. Flagging for team attention to see if anyone can recall if there was a reason for the current approach.

Comment From: snicoll

In the current arrangement we have a @Configuration class with no hook-point to do something so we chose to add @Autowired for the lack of a better option. I agree it is unusual.

We considered switching those to implement SmartInitializingSingletonat some point but I can't find back the issue where this was discussed (if any). IMO, anything that gets rid of those and better use Micrometer's infrastructure is an improvement.

Comment From: wilkinsona

Thanks, @snicoll. A MeterBinder-based approach seems to work fine. These changes build cleanly at least. I am quite tempted to merge them.

Comment From: philwebb

We're going to merge the above fix, but only in 2.7 since there's some risk involved. For 2.5 and 2.6, please use the workaround above.