[英]Spring Boot and Azure: initialise bean before auto-configuration
尝试设置 Sprint 启动应用程序以从Azure 应用程序配置加载 配置,并参考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
类上使用@Primary
@AutoConfigureBefore(AzureConfigBootstrapConfiguration.class)
,但没有一种替代方法有效。
问题:你知道如何在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.