在 Spring 中将默认属性值指定为 NULL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16735141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:59:41  来源:igfitidea点击:

Specify default property value as NULL in Spring

springpropertiesnulldefault-value

提问by Ondrej Bozek

I want to define default property value in Spring XML configuration file. I want this default value to be null.

我想在 Spring XML 配置文件中定义默认属性值。我希望这个默认值是null.

Something like this:

像这样的东西:

...
<ctx:property-placeholder location="file://${configuration.location}" 
                          ignore-unresolvable="true" order="2" 
                          properties-ref="defaultConfiguration"/>

<util:properties id="defaultConfiguration">
    <prop key="email.username" >
        <null />
    </prop>  
    <prop key="email.password">
        <null />
    </prop>  
</util:properties>
...

This doesn't work. Is it even possible to define nulldefault values for properties in Spring XML configuration?

这不起作用。甚至可以null在 Spring XML 配置中为属性定义默认值吗?

回答by Anton Kirillov

It is better to use Spring EL in such way

最好以这种方式使用 Spring EL

<property name="password" value="${email.password:#{null}}"/>

it checks whether email.passwordis specified and sets it to null(not "null"String) otherwise

它检查是否email.password指定并将其设置为null(非"null"字符串)否则

回答by Andrei Cojocaru

have a look at PropertyPlaceholderConfigurer#setNullValue(String)

看看PropertyPlaceholderConfigurer#setNullValue(String)

It states that:

它指出:

By default, no such null value is defined. This means that there is no way to express null as a property value unless you explictly map a corresponding value

默认情况下,没有定义这样的空值。这意味着无法将 null 表示为属性值,除非您显式映射相应的值

So just define the string "null" to map the null value in your PropertyPlaceholderConfigurer:

因此,只需定义字符串“null”来映射 PropertyPlaceholderConfigurer 中的 null 值:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="nullValue" value="null"/>
    <property name="location" value="testing.properties"/>
</bean>

Now you can use it in your properties files:

现在你可以在你的属性文件中使用它:

db.connectionCustomizerClass=null
db.idleConnectionTestPeriod=21600

回答by YoK

You can try use Spring EL.

您可以尝试使用 Spring EL。

<prop key="email.username">#{null}</prop>

回答by EpicPandaForce

It appears you can do the following:

看来您可以执行以下操作:

@Value("${some.value:null}")
private String someValue;

and

@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfig() {
    PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    propertySourcesPlaceholderConfigurer.setNullValue("null");
    return propertySourcesPlaceholderConfigurer;
}