Skip to content

Instantly share code, notes, and snippets.

@pavelfomin
Last active November 13, 2024 15:09
Show Gist options
  • Save pavelfomin/a23574b13f30331a2c49f583e57ad1b2 to your computer and use it in GitHub Desktop.
Save pavelfomin/a23574b13f30331a2c49f583e57ad1b2 to your computer and use it in GitHub Desktop.
Specify custom query for DataSourceHealthIndicator in Spring Boot 3

For some reason, DataSourceHealthIndicator does not support custom query configuration via a property. DataSourceHealthContributorAutoConfiguration uses poolMetadata.getValidationQuery() to pass the validation query to DataSourceHealthIndicator.

Using spring.datasource.hikari.connection-test-query will customize the Hikari datasource test query and db health check will also it. However, it will also affect the performance of the Hikari connection pool which is not ideal.

Another way of configuring a custom query for DataSourceHealthIndicator is to create this as a @Bean manually and pass a custom query to its constructor. Using the same @Bean name dbHealthIndicator disables the autoconfiguration of the default DataSourceHealthIndicator. Otherwise, both default and custom versions of DataSourceHealthIndicator can be inluded in the health check endpoint.

@Configuration
public class DataSourceHealthIndicatorConfiguration {
static final String SCHEMA = "foo";
public static final String QUERY = "select installed_rank from %s.flyway_schema_history limit 1".formatted(SCHEMA);
@Bean("dbHealthIndicator")
public DataSourceHealthIndicator dataSourceHealthIndicator(DataSource dataSource) {
return new DataSourceHealthIndicator(dataSource, QUERY);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment