java - 为什么 Spring Value 中的默认值不能防止 NULL 错误?

标签 java spring spring-el

我在 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/

相关文章:

java - 如何为 spring 应用程序设置 Multi-Tenancy 环境?

java - 没有检索到 GPS 更新?代码有问题?

Java:使用定界符摆脱大写字母单词?

java - 如何重构使用 spring Autowiring 的代码库

spring - Spring多线程与 hibernate

java - Spring SpEL 条件

java - 解析 View 中的 Spring EL 变量

java - 继承指定Type的泛型类时会发生Type Erasure吗?

java - 如何解决(上下文: this)

java - 将任意对象注入(inject) Spring bean