我有一个配置文件,其中包含应在其中注入(inject)值的字段。我有一个属性(property):
@Value("${other.app.start.script:}")
private String startScript;
注入(inject)到这个属性中的值是这样的:
/app/${version}/otherAppStarter.bat
因此,当 Context 启动时,Spring 会尝试解析 ${version}。但我需要在某些进程运行期间的其他时间解析该值。并且 ${version} 可能会在主应用程序运行期间发生更改。
有没有办法告诉 Spring 不要解析 ${version} 占位符。 我可以将 ${version} 更改为类似 #[version] 的内容,然后 Spring 将不会解析此占位符,但也许有办法使用一些 native Spring 功能。
谢谢!
最佳答案
您可以注册一个static
bean,它扩展PropertySourcesPlaceholderConfigurer
并重写其方法convertPropertyValue
。
public class MyPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer {
@Override
protected String convertPropertyValue(String originalValue) {
if (originalValue.contains("${version}")) {
return originalValue;
}
return super.convertPropertyValue(originalValue);
}
}
如果您通过 @PropertySource
使用 Java 配置,则还需要重写方法 doProcessProperties
,如 Spring Jira SPR-8928 中所述。 :
@Override
protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
StringValueResolver valueResolver) {
super.doProcessProperties(beanFactoryToProcess,
new StringValueResolver() {
@Override
public String resolveStringValue(String strVal) {
return convertPropertyValue(valueResolver.resolveStringValue(strVal));
}
});
}
Java 配置的示例如下所示:
@Configuration
@PropertySource("classpath:saml/saml.properties")
public class MyConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer myPlaceholderConfigurer() {
return new MyPlaceholderConfigurer();
}
}
关于java - Spring:如何避免自动解析特定占位符的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39476859/