How to externalize configuration in spring?

2019-07-23 21:14发布

问题:

I am attempting to externalize the configurations using spring, but cannot get it to work properly..

Here is what I did so far:

create a property file inside the war file (src/test/resources/) for each environment. For example: nonprod-key.properties & prod-key.properties with content like so:

    key.name=NameOfPrivateKey.pfx
    key.password=JustAPasswordForPrivateKey

Then in my jboss-cxf.xml, I would like to read the above value as follows:

    <import resource="#{systemProperties['environment']}-key.properties" />

    <http:conduit name="*.http-conduit">
        <http:tlsClientParameters
            secureSocketProtocol="SSL">
            <sec:keyManagers keyPassword="${key.password}">
                <sec:keyStore type="PKCS12" password="${key.password}" resource="${key.name}" />
            </sec:keyManagers>
            ...  ... ...
        </http:tlsClientParameters>
    </http:conduit>

And then in eclipse, run configurations --> Arguments --> VM Arguments

    -Denvironment=nonprod

Unfortunately, the above does not work. :(

I am getting this error message:

    class path resource [#{systemProperties['environment']}-key.properties] cannot be opened because it does not exist

I was attempting to use the suggestion from here : http://forum.springsource.org/showthread.php?98988-Access-external-properties-file-from-SPRING-context-file&p=332278#post332278

But cannot seem to get it to work. What am I doing wrong? Could someone please give an example/sample of how best to do accomplish this.

Thank you.

-SGB

回答1:

I believe one needs to be on Spring 3.1.x to use profiles. We are not ... yet.

Anyways, the final solution that seems to work for us is to use :

<context:property-placeholder location="classpath:${environment}-key.properties"/>

instead of

<import resource="#{systemProperties['environment']}-key.properties" />

Everything else is same as listed in my original post (question).

Hope someone finds this useful.

SGB



回答2:

You can use Property Place Holder. If you want a flexible configuration, eg. a default configuration stored in your war which can be overrided by an external configuration, you can use directly the PropertyPlaceholderConfigurer bean like :

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:ignoreResourceNotFound="true">
    <property name="locations">
        <array>
            <bean class="org.springframework.core.io.ClassPathResource" c:path="${environment}-key.properties"/>
            <bean class="org.springframework.core.io.FileSystemResource" c:path="relative/path"/>
        </array>
    </property>
</bean>

path attributes can used SPEL for example to reference property or system env variable.

Have a look to this article and this how to read System environment variable in Spring applicationContext