【发布时间】:2019-06-18 13:06:03
【问题描述】:
我正在尝试从 git hub 中获取价值,它有一个属性文件,比如 abc.properties。我需要从属性文件中读取值并将其注入到 bean 类变量中
【问题讨论】:
标签: spring-boot spring-boot-actuator
我正在尝试从 git hub 中获取价值,它有一个属性文件,比如 abc.properties。我需要从属性文件中读取值并将其注入到 bean 类变量中
【问题讨论】:
标签: spring-boot spring-boot-actuator
您可以使用@PropertySource 和@Configuration 的组合将任何本地属性文件绑定到bean 的字段中。
例如:
@Configuration
@PropertySource("file:/path/to/abc.properties")
public class AbcProperties {
private String someProperty;
private int anotherProperty;
// standard getters and setters
}
这假定文件位于本地。请注意,@PropertySource 也可以引用类路径相关文件(如果它们在您的项目中)。
如果您真的想在运行时从 GitHub 远程读取文件,您可能需要自定义 PropertySourcesPlaceholderConfigurer 或考虑使用 Spring Cloud Config 来管理外部配置。
【讨论】:
@PropertySource 和@Configuration 创建一个包含配置的bean,然后您可以将该配置bean 自动装配到您需要的位置。如果文件是远程文件,我认为您最好的选择是自定义PropertySourcesPlaceholderConfigurer ,它读取远程文件(并处理所有故障场景,如网络超时)以将其加载到 Spring 环境中。
PropertySource 用于将外部文件绑定到 bean 的字段中,而 PropertyPlaceholderConfigurer 用于定义在值中找到 ${...} 占位符时解析它们的策略。