Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring property configuration syntax?

Tags:

java

spring

I've run across an odd syntax in a Spring XML file:

<bean id="mySessionFactory" class="my.thingy.session.SessionFactoryImpl">
    <property name="myPropertyName">
        <!-- WHAT IS THIS VALUE?  -->
        <value>${process.file.thing:propname.server}</value>
    </property>
</bean>

I'm not familiar with the syntax of the ${value1:value2} placeholder - what is the first value value1 doing there? Is it a classpath, a package name, a folder name or what? I've searched for some explanation of this, but it's apparently undocumented (at least as far as I can tell.)

like image 908
user1071914 Avatar asked Oct 27 '25 09:10

user1071914


1 Answers

I'm not familiar with the syntax of the ${value1:value2} placeholder

It's Spring Expression Language's PropertySourcesPlaceholderConfigurer fallback value mechanism. The value2 serves as a default value for value1. If value1 was present, it will used. otherwise, value2 will be used and in that case, value2 is just a literal.

${process.file.thing:propname.server}

In this case, spring first tries to resolve a property named process.file.thing from its environment. If it succeeds, it will use that value. Otherwise, the propname.server literal will be used.

PropertyPlaceholderHelper's parseStringValue method is responsible for resolving the default value. This method looks like this:

String propVal = placeholderResolver.resolvePlaceholder(placeholder);
if (propVal == null && this.valueSeparator != null) {
    int separatorIndex = placeholder.indexOf(this.valueSeparator);
    if (separatorIndex != -1) {
        String actualPlaceholder = placeholder.substring(0, separatorIndex);
        String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
        propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
        if (propVal == null) {
            propVal = defaultValue;
        }
    }
}

This feature has been described here in PlaceholderConfigurerSupport's javadoc:

Default property values can be defined globally for each configurer instance via the properties property, or on a property-by-property basis using the default value separator which is ":" by default and customizable via setValueSeparator(String).

like image 97
Ali Dehghani Avatar answered Oct 28 '25 22:10

Ali Dehghani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!