gpt4 book ai didi

java - 以编程方式加载 Spring 属性文件

转载 作者:行者123 更新时间:2023-12-02 00:02:45 24 4
gpt4 key购买 nike

如果文件位于类路径上,这就是我加载 application.properties 的方式。

@ComponentScan
@Configuration
@PropertySource("classpath:application.properties")
public class MyApplication {
// Have some public methods
}

public class Application {

public static void main(String[] args) {

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyApplication.class);
MyApplication app = context.getBean(MyApplication.class);

// execute methods in app

}
}

我们正在尝试部署应用程序,其中属性文件外部存储在 Google Cloud 存储桶 (GCS) 上。我可以从 GCS 加载属性文件并将其保存在内存中。如何将属性传递到应用程序上下文并覆盖从类路径加载的属性?

如果重要的话,它是一个独立的应用程序,而不是 Spring Boot。

最佳答案

如果你的内存中有它,那么这应该不是问题。摆脱 @PropertySource("classpath:application.properties") 注解并手动注册 PropertySourcesPlaceholderConfigurer bean。

@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
properties.setLocation([any implementation of Resource interface - use most applicable out of available or implement it by yourself]);
return properties;
}

关于java - 以编程方式加载 Spring 属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58171460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com