Using Maven <Resource> directive in conjunction with Spring PropertyPlaceholderConfigurer

Using Maven <Resource> directive in conjunction with Spring PropertyPlaceholderConfigurer allows maven variables to influence the run-time application property resolution.

Following from page Maven variables substitution in resource files during maven build, given that appbase is the specified directory from which maven build process will read resource files
<build>
  .....   
  <resources>
    <resource>
      <directory>appbase</directory>
      <filtering>true</filtering>
    </resource>
  </resources>
  
  ..... 
  
</build>
and spit out the maven-variable substituted recreation of those resource files into
/WEB-INF/classes/ 

In the file

/durian/appbase/properties/a.properties
there is a property declaration
maxUsers = ${durian.maxUsers}
There is a corresponding property definition in the pom.xml
<properties>
  <durian.maxUsers>8</durian.maxUsers>
</properties>
After maven build, the deployed property file will be
/durian/target/durian/WEB-INF/classes/properties/a.properties
The property declaration has resolved to be
maxUsers = 8

PropertyPlaceholderConfigurer declared in Spring config registers the application properties from the specified property files to allow them to be accessed during run-time.
<bean
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location">
    <value>classpath:properties/a.properties</value>
  </property>
</bean>
The property named location specifies the location of the property file, whose property definitions are to be exposed to Spring context. To expose properties from multiple property files, the property named locations is used:
<bean
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
     <list>
        <value>classpath:properties/a.properties</value>
        <value>classpath:properties/b.properties</value>
        <value>/user.properties</value>
     </list>
  </property>
</bean>

Alternatively,
<context:property-placeholder
    location="classpath:properties/a.properties" ignore-unresolvable=”true”/>
<context:property-placeholder
    location="classpath:properties/b.properties"/>
Having a property-placeholder declaration per property file, which will be resolved n the order they are declared. All property-placeholder declarations, except the last one, should have the attribute ignore-unresolvable=”true”, to allow distributing properties over more than one locations without encountering unresolvable property error..

No comments:

Post a Comment