July 26, 2005

Multiple, separate PropertyPlaceholderConfigurers in Spring

several PropertyPlaceholderConfigurer instances in a AppCtx? - I'm building a custom lightweight application server at work with Spring as its core. Any number of applications can be deployed to it; they're discovered at runtime so deployment is a file-copy. Each application has its own Spring context and settings and to ensure we have writable configuration in an easy-to-read format some of the bean settings are brought in at runtime from properties files. Spring provides the PropertyPlaceholderConfigurer for this, so that's easy glue. (Dion had a good post about this almost a year ago.)

However, if you want to reference multiple configurers that don't know about each other you'll run into a problem. At first it will appear that you can only define one configurer because some settings won't be replaced properly, but that's a red herring. What happens is that behind the scenes Spring associates each configurer with parsing rules so it knows which configurer is supposed to replace which placeholders. Therefore you've got to provide some disambiguation to this parser. Fortunately it's easy:

    <bean id="appASettings"
        <property name="location" value="appA_settings.properties" />
        <property name="placeholderPrefix" value="$A{" />
    <bean id="appADataSource" 
        <property name="driverClassName" value="$A{db.driver}" />
        <property name="url"             value="$A{db.url}" />

As long as every application has its own prefix its settings will never get stomped on by any other and you can presumably add as many configurers as you need. What's most interesting about this is that the complexity behind this is only revealed if you need it. IMO most open-source projects -- and, to a lesser extent, all software -- have a hard time with this principle, burdening you with lots of configuration to do even simple things.

Next: That new iBook...
Previous: Questions Snopes doesn't answer