我在 Java 代码中对我的属性进行了以下定义:
import org.springframework.beans.factory.annotation.Value;
...
@Value("#{sdProperties['is.test.server'] ?: false }")
private boolean isTestServer = false;
还在 XML 配置文件中我有:
<util:properties id="sdProperties">
<prop key="sdzootest.server.url">${sdzootest.server.url}</prop>
<prop key="is.test.server">${is.test.server}</prop>
</util:properties>
如果属性文件中未指定 is.test.server
,我仍然会收到错误:
2016-04-06 15:52:00,161 [localhost-startStop-1] ERROR com.elasticpath.web.context.impl.EpContextConfigListener:69 - Caught an exception. org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name sdProperties defined in null: Could not resolve placeholder 'is.test.server' in string value "${is.test.server}"
最佳答案
PlaceholderConfigurerSupport
有一个特殊属性ignoreUnresolvablePlaceholders
If a configurer cannot resolve a placeholder, a BeanDefinitionStoreException will be thrown. If you want to check against multiple properties files, specify multiple resources via the locations property. You can also define multiple configurers, each with its own placeholder syntax. Use ignoreUnresolvablePlaceholders to intentionally suppress throwing an exception if a placeholder cannot be resolved.
目前尚不清楚如何设置占位符支持,因此这里有几个选项:
<context:property-placeholder
ignore-unresolvable="true"
location="classpath:app.properties"/>
或
@Bean
public PropertySourcesPlaceholderConfigurer ppc() {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
关于java - 为什么 Spring Value 中的默认值不能防止 NULL 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461922/