我正在考虑将我的Spring XML配置迁移到Java中。我在使用占位符配置器时遇到了一些问题。
在XML中,我将"位置设置为">
<property name="locations">
<list>
...
<value>file:////${project.home}/conf/jdbc.properties</value>
</list>
</property>
,其中"project.home"是我用"-Dproject.home=..."设置的参数。">
现在,我不确定如何使用Java执行此操作,因为我不能只使用
new FileSystemResource("file:////${project.home}/conf/jdbc.properties"),
那么,如果我想将 PropertySourcesPlaceholderConfigurer.setLocations 与 system.property 一起使用,我该怎么做?指点赞赏。
context:property-placeholder和@Value注释的组合可用于轻松地将一组属性注入 Spring Beans。
以下是完成此操作的 3 步过程:
步骤 1:在"键=值">类型文件中定义所有必需的属性
应用程序属性
步骤 2:使用属性占位符指定 application.properties 文件在 Bean 配置中的位置
步骤3:在Java程序中使用@Value注释来获取属性。
下面是一个工作示例的代码片段:
步骤 1:以"键=值"格式定义属性
# File name: application.properties
db.schema=my_schema
db.host=abc.xyz.com:3306
db.table=my_table
步骤 2:使用属性占位符提及属性文件的位置
<beans xmlns="http://www.springframework.org/schema/beans" ...>
<context:property-placeholder location="classpath:application.properties"/>
<!-- other content -->
</beans>
步骤 3:使用@Value注释获取属性
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
public class MyProgram {
@Value("${db.host}")
private String dbHost;
@Value("${db.schema}")
private String dbSchema;
@Value("${db.table}")
private String dbTable;
@Override
public void showConfig() {
System.out.println("DB Host = " + dbSchema);
System.out.println("DB Schema = " + dbSchema);
System.out.println("DB Table = " + dbSchema);
}
}
调用 showConfig(( 的输出
DB Host = abc.xyz.com:3306
DB Schema = my_schema
DB Table = my_table
更多信息:
https://memorynotfound.com/load-properties-spring-property-placeholder/
https://memorynotfound.com/loading-property-system-property-spring-value/
https://mkyong.com/spring/spring-propertysources-example/
System.getProperty 将为您提供使用 -D java 选项的属性集
由于您尝试使用自定义位置调用PropertySourcesPlaceholderConfigurer.setLocations()
,因此您可能应该使用@PropertySource
注释。
@Configuration
@PropertySource(value="file://#{systemProperties['project.home']}/conf/jdbc.properties")
public class MyConfig {
}
如果您需要更细粒度的控制,例如,如果您的位置使用模式,您还可以配置 BeanPropertySourcesPlaceholderConfigurer
。有关更多详细信息,请参阅此答案。