设置Spring引导.以编程方式设置Yaml值



我想以编程方式设置bootstrap.yaml属性aws.paramstore.prefix

根据文档,配置它的唯一方法是通过bootstrap.yaml文件。如果我在bootstrap.yaml文件中定义aws.paramstore.prefix,它就可以正常工作。但是,我想通过编程来实现。

也有可能自定义引导属性源,但这并不能解决问题。自定义引导程序似乎比aws.paramstore属性加载得晚。

据我所知,aws.paramstore属性是在使用spring.factories时很早就加载的,这些属性是在spring-cloud-starter-aws-parameter-store-configdependency中定义的:

org.springframework.cloud.bootstrap.BootstrapConfiguration=
org.springframework.cloud.aws.autoconfigure.paramstore.AwsParamStoreBootstrapConfiguration

AwsParamStoreBootstrapConfiguration构造函数中,AwsParamStoreProperties作为参数传递,通过@ConfigurationProperties实例化。那就是aws.paramstore很早就被载入了

您可以尝试查看在Spring Context初始化的最初阶段执行的PostProcessors。例如,EnvironmentPostProcessor。它执行得相当早,可能可以帮助你在加载到上下文之前管理一些属性/修改文件。

注意:如果你想在其他项目的库中使用这些代码,你应该在spring中添加这样的PostProcessor。工厂文件。在其他情况下,它不会被添加到另一个Spring的配置阶段。

在调用SpringApplication#run方法之前设置aws.paramstore.prefix属性。

假设我们希望将aws.paramstore.prefix设置为正在传递给应用程序的Spring配置文件的值。然后可以这样做:

public static void main(String[] args) {
// or System.getenv("SPRING_PROFILES_ACTIVE")
// or some additional logic that filters a profile that is being passed to the application
// note that application can also have multiple profiles
String activeProfile = System.getProperty("spring.profiles.active");
System.setProperty("aws.paramstore.prefix", activeProfile);
SpringApplication.run(MyApplication.class, args);
}

这样我们就可以保证。在spring.factories启动之前,aws.paramstore.prefix是可用的。

最新更新