问题
I want to define default property value in Spring XML configuration file. I want this default value to be 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 null default values for properties in Spring XML configuration?
回答1:
It is better to use Spring EL in such way
<property name="password" value="${email.password:#{null}}"/>
it checks whether email.password is specified and sets it to null (not "null" String) otherwise
回答2:
have a look at 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
So just define the string "null" to map the null value in your PropertyPlaceholderConfigurer:
<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
回答3:
You can try use Spring EL.
<prop key="email.username">#{null}</prop>
回答4:
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;
}
来源:https://stackoverflow.com/questions/16735141/specify-default-property-value-as-null-in-spring