【问题标题】:Why default value in Spring Value does not prevent the NULL error?为什么 Spring Value 中的默认值不能防止 NULL 错误?
【发布时间】:2016-04-06 20:41:04
【问题描述】:

我在 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] 错误 com.elasticpath.web.context.impl.EpContextConfigListener:69 - 捕获 一个例外。 org.springframework.beans.factory.BeanDefinitionStoreException: 无效的 bean 定义,名称为 sdProperties 在 null 中定义:可能 不解析字符串值中的占位符“is.test.server” "${is.test.server}"

【问题讨论】:

  • 我猜你需要&lt;prop key="is.test.server"&gt;${is.test.server}&lt;/prop&gt; 的默认值。试试&lt;prop key="is.test.server"&gt;${is.test.server:default}&lt;/prop&gt;

标签: java spring spring-el


【解决方案1】:

PlaceholderConfigurerSupport 有一个特殊的属性ignoreUnresolvablePlaceholders

如果配置器无法解析占位符,则 将抛出 BeanDefinitionStoreException。如果你想检查 针对多个属性文件,通过指定多个资源 位置属性。您还可以定义多个配置器,每个 具有自己的占位符语法。使用 ignoreUnresolvablePlaceholders 来 如果占位符不能,故意抑制抛出异常 得到解决。

不清楚你如何设置占位符支持,所以这里有几个选项:

<context:property-placeholder
        ignore-unresolvable="true"
        location="classpath:app.properties"/>

@Bean
public PropertySourcesPlaceholderConfigurer ppc() {
    PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
    ppc.setIgnoreUnresolvablePlaceholders(true);
    return ppc;
}

【讨论】:

  • 我尝试在配置文件中添加 context:property-placeholder - 没有帮助。我尝试了 sd.properties 和 app.properties。关于第二个建议 - 它应该在 @Configuration 文件中吗?
  • @AlexNarinsky 是的,方法应该在标有@Configuration注解的类中
猜你喜欢
  • 2012-08-13
  • 1970-01-01
  • 2019-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
  • 2017-08-12
相关资源
最近更新 更多