简体   繁体   中英

Override Spring properties with VM options

I want to achieve the following behavior:

I use property files with Spring ResourceBundleMessageSource with properties like this:

my.prop=42

Now I want to override properties with VM options like this:

-Dmy.prop=13

How can I do this in a simple and transparent way?

Thanks!

Use your MessageSource only for language Strings.

Use property files for properties.

Now you can load your properties files with org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

In your XML, instead of using the default value which is SYSTEM_PROPERTIES_MODE_FALLBACK, set it to use SYSTEM_PROPERTIES_MODE_OVERRIDE.

You can now load your props using the @Value annotations, and the VM options will override the values you set in your properties file

Example:

So call your MessageSource messages.properties

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages"/>
    <property name="fileEncodings" value="UTF-8"/>
    <property name="defaultEncoding" value="UTF-8"/>
</bean>

And call your properties file misspiggy.properties (or something else :))

<bean id="propertyLoader" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreResourceNotFound" value="false"/>
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
    <property name="fileEncoding" value="UTF-8"/>
    <property name="locations">
        <list>
            <value>classpath:misspiggy.properties</value>
        </list>
    </property>
</bean>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM