Search code examples
javaspringspring-bootazure-keyvaultazure-app-configuration

Spring Boot and Azure: initialise bean before auto-configuration


Trying to setup a Sprint Boot Application to load configurations from Azure App Configuration, with a reference to a Azure Key Vault entry for properties with sensitive information.

Using App Configuration is working properly and problems emerge when the Key Vault reference is added to App Configuration.

In order to connect to Key Vault, AzureConfigBootstrapConfiguration looks for a KeyVaultCredentialProvider bean, which is not available when it is loaded:

@Bean
    public AzureConfigPropertySourceLocator sourceLocator(AzureCloudConfigProperties properties,
            AppConfigProviderProperties appProperties, ClientStore clients, ApplicationContext context) {
        KeyVaultCredentialProvider keyVaultCredentialProvider = null;
        try {
            keyVaultCredentialProvider = context.getBean(KeyVaultCredentialProvider.class);
        } catch (NoUniqueBeanDefinitionException e) {
            LOGGER.error("Failed to find unique TokenCredentialProvider Bean for authentication.", e);
            if (properties.isFailFast()) {
                throw e;
            }
        } catch (NoSuchBeanDefinitionException e) {
            LOGGER.info("No TokenCredentialProvider found.");
        }
        return new AzureConfigPropertySourceLocator(properties, appProperties, clients, keyVaultCredentialProvider);
    }

Tried to create the bean with highest precedence but it is not working:

@Configuration
public class DemoConfiguration {
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public KeyVaultCredentialProvider keyVaultCredentialProvider() {
        return uri -> new EnvironmentCredentialBuilder().build();
    }
}

Also tried using @Primary and @Priority on bean, and @AutoConfigureBefore(AzureConfigBootstrapConfiguration.class) on DemoConfiguration class, but none of the alternatives work.

Question: Do you know how to create the KeyVaultCredentialProvider bean before AzureConfigBootstrapConfiguration is initialised?


Solution

  • Solution:

    Since Azure App Configuration uses BootstrapConfiguration, solution is to create the META-INF/spring.factories file to enable the configuration with the required bean, such as:

    org.springframework.cloud.bootstrap.BootstrapConfiguration=\
    org.davidcampos.autoconfigure.DemoConfiguration