不必使用系统属性。但是,您必须在构建期间解析占位符。
将您的属性放在对象中,如下所示:
<bean id="cacheProperties" class="java.util.Properties">
<constructor-arg>
<props>
<prop key="prop1">#{prop1}</prop>
<prop key="prop2">#{prop2}</prop>
</props>
</constructor-arg>
</bean>
并将它们设置为您的自定义 PlaceHolderHelper:
<bean id="cachePlaceholderHelper"
class="com.PlaceholderHelper" depends-on="cacheProperties">
<property name="configFileResource" value="classpath:cacheConfig.xml"/>
<property name="properties" ref="cacheProperties"/>
</bean>
PlaceholderHelper 可能看起来像这样:
private Resource configFileResource;
private Properties properties;
private Resource resolvedConfigResource;
@PostConstruct
public void replace() throws IOException {
PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}");
if (this.properties != null && this.configFileResource != null) {
File file = this.configFileResource.getFile();
String content = FileUtils.readFileToString(file);
String result = helper.replacePlaceholders(content, this.properties);
File resolvedCacheConfigFile = new File("resolvedCacheConfig");
FileUtils.write(resolvedCacheConfigFile, result);
resolvedConfigResource = new FileSystemResource(resolvedCacheConfigFile);
logger.info(String.format("Placeholders in file %s were replaced.", file.getName()));
}
}
将p:configLocation更改为已解析的资源:
p:configLocation="#{cachePlaceholderHelper.resolvedConfigResource}
现在您可以在 XML 的任何地方使用 ${prop1} 表达式。