【发布时间】:2015-05-30 21:28:40
【问题描述】:
我无法将以下配置转换为 java 配置。
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<property name="ignoreResourceNotFound" value="true"/>
<property name="locations">
<list>
<value>classpath*:META-INF/spring/environments/${XXX_env}/*.properties</value>
<value>file:/etc/XXX/database.properties</value>
</list>
</property>
</bean>
在上面的例子中,XXX_env 是一个环境变量。例如,
export XXX_env=dev
如何将其转换为 Spring Java 配置?这是我的尝试:
@Bean
public PropertyPlaceholderConfigurer propertyConfigurer() throws IOException {
PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
props.setIgnoreResourceNotFound(true);
props.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
Resource[] locations;
PathMatchingResourcePatternResolver classPathResources = new PathMatchingResourcePatternResolver();
locations = classPathResources.getResources("classpath*:META-INF/spring/environments/"+env()+ "/*.properties");
props.setLocations(locations);
Resource location = new FileSystemResource("/etc/XXX/database.properties");
props.setLocation(location);
return props;
}
private String env(){
Map<String, String> env = System.getenv();
return env.get("XXX_env");
}
@Value("${database.password}")
private String databasePassword;
@Value("${database.url}")
private String databaseUrl;
@Value("${database.username}")
private String databaseUsername;
@Value("${database.driverClassName}")
private String databaseDriverClassName;
【问题讨论】:
-
为什么不能,是什么问题?
-
让我更新问题。
-
env()有问题吗?你也可以使用 Spring 的Environment,它是可注入的。 -
我认为问题在于从类路径下的目录加载 *.properties 时正则表达式匹配。
标签: java spring spring-mvc properties configuration