使用Spring框架时,我需要一些特定于环境(dev|test|prod)的属性。我只有一个配置文件(myapp.properties),但由于某些原因我不能拥有多个配置文件(即使Spring可以处理多个配置文件)。
因此,我需要添加带有前缀的属性的可能性,例如
dev.db.user=foo
prod.db.user=foo
并且告诉应用程序使用哪个前缀(环境)与 VM 参数一起使用,例如 -Denv-target
或类似的东西。
使用Spring框架时,我需要一些特定于环境(dev|test|prod)的属性。我只有一个配置文件(myapp.properties),但由于某些原因我不能拥有多个配置文件(即使Spring可以处理多个配置文件)。
因此,我需要添加带有前缀的属性的可能性,例如
dev.db.user=foo
prod.db.user=foo
并且告诉应用程序使用哪个前缀(环境)与 VM 参数一起使用,例如 -Denv-target
或类似的东西。
PropertyPlaceholderConfigurer
的子类来实现这个目的:public class EnvironmentPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
private static final String ENVIRONMENT_NAME = "targetEnvironment";
private String environment;
public EnvironmentPropertyPlaceholderConfigurer() {
super();
String env = resolveSystemProperty(ENVIRONMENT_NAME);
if (StringUtils.isNotEmpty(env)) {
environment = env;
}
}
@Override
protected String resolvePlaceholder(String placeholder, Properties props) {
if (environment != null) {
String value = props.getProperty(String.format("%s.%s", environment, placeholder));
if (value != null) {
return value;
}
}
return super.resolvePlaceholder(placeholder, props);
}
}
并将其用于applicationContext.xml
(或任何其他Spring配置文件)中:
<bean id="propertyPlaceholder"class="EnvironmentPropertyPlaceholderConfigurer">
<property name="location" value="classpath:my.properties" />
</bean>
在my.properties
文件中,您可以定义属性,例如:
db.driverClassName=org.mariadb.jdbc.Driver
db.url=jdbc:mysql:///MyDB
db.username=user
db.password=secret
prod.db.username=prod-user
prod.db.password=verysecret
test.db.password=notsosecret
这样,您就可以通过环境键(例如prod
)为属性键添加前缀。
使用vm参数targetEnvironment
,你可以选择你想使用的环境,例如-DtargetEnvironment=prod
。
如果不存在特定于环境的属性,则选择默认属性(不带前缀)。 (总是应该定义一个默认值。)
我不知道您避免拥有多个配置文件的限制是什么,但您可以使用类似于-Denvtarget=someValue的东西,并在Java中执行以下操作:
//Obtain the value set in the VM argument
String envTarget= System.getProperty("env-target");
Properties properties;
try {
properties = PropertiesLoaderUtils.loadAllProperties("myapp.properties");
} catch (IOException exception) {
//log here that the property file does not exist.
}
//use here the prefix set in the VM argument.
String dbUser = properties.getProperty(envTarget+".db.user");
<property name="username" value="${${env-target}.database.username}" />
<property name="password" value="${${env-target}.database.password}" />
同时确保您使用了正确配置的property-placeholder:
<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
或者,如果您使用特殊的属性配置器(例如EncryptablePropertyPlaceholderConfigurer),请设置以下属性:
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
但是,正如之前提到的那样,最好使用配置文件。