Spring 引导和 Azure:在自动配置之前初始化 bean

Spring Boot and Azure: initialise bean before auto-configuration

正在尝试设置 Sprint 引导应用程序以从 Azure App Configuration, with a reference to a Azure Key Vault 条目加载具有敏感信息的属性配置。

使用应用程序配置工作正常,但在将 Key Vault 引用添加到应用程序配置时出现问题。

为了连接到 Key Vault,AzureConfigBootstrapConfiguration 寻找一个 KeyVaultCredentialProvider bean,它在加载时不可用:

@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);
    }

已尝试创建具有最高优先级的 bean,但它不起作用:

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

也尝试在 bean 上使用 @Primary@Priority,在 DemoConfiguration class 上使用 @AutoConfigureBefore(AzureConfigBootstrapConfiguration.class),但是 none 的替代方案有效.

问题: 你知道如何在 AzureConfigBootstrapConfiguration 初始化之前创建 KeyVaultCredentialProvider bean 吗?

如果不知道确切的异常和在您的案例中抛出的堆栈跟踪,就很难给出任何提示。

但如果确实是运行时缺少配置,另一种强制执行您自己的配置顺序的方法是:

public static void main(String[] args) {
    SpringApplication.run(
       new Class[]{ YourSpringBootApplication.class,
           KeyVaultCredentialProvider.class, 
           AzureConfigBootstrapConfiguration.class // , ...
       }, args);
}

Class 数组包含要在应用程序启动时加载的主要来源列表。所以这个列表不需要包含所有的组件和配置。

你在你的 spring.factories 中设置了 DemoConfiguration 了吗?

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.DemoConfiguration

应该可以找到它。

解法:

由于 Azure App Configuration 使用 BootstrapConfiguration,解决方案是创建 META-INF/spring.factories 文件以使用所需的 bean 启用配置,例如:

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