August 02, 2015

SpringMVC: PropertyPlaceHolder

Another interesting support feature provided by Spring is using properties in your code through PropertyPlaceholderConfigurer. It helps load application properties from either a file or database table. The XML for using both,which will go into your spring context file,is 

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="properties">
        <bean class="org.apache.commons.configuration.ConfigurationConverter"
             factory-method="getProperties">
                 <constructor-arg>
                   <bean class="org.apache.commons.configuration.DatabaseConfiguration">
                          <constructor-arg ref="<database bean>" />
                          <constructor-arg value="<database property table>" />
                          <constructor-arg value="<tablecolumn for placeholdernames>" />
                          <constructor-arg value="<tablecolumn for placeholdervalues>" />
                   </bean>
                </constructor-arg>
        </bean>
     </property>
     <property name="locations">
         <list>
            <value>file:src/main/webapp/WEB-INF/application.properties</value>
         </list>
     </property>
</bean>

<constructor-arg value="datasource" /> refers to a database bean defined in the spring context xml.

<constructor-arg value="app_config" /> refers to a database table APP_CONFIG.

<constructor-arg value="config_key" /> refers to column 'CONFIG_KEY' in APP_CONFIG that will contain the property you want to use in your code.

<constructor-arg value="config_value" />  refers to column 'CONFIG_VALUE' in APP_CONFIG that will contain the corresponding value of the property.


The below example shows how to then use the pre-loaded properties in your Spring code.


@Controller
public class DocumentController{

     @Value("${doc_Base}")
      String docBase="";
      @Value("${app_Env}")
      String appEnv=null;
      @Value("${doc_Path}")
      String docPath="";

      @Autowired
      private DocumentDAO documentDao;

      @Autowired
      private UserDAO userDao;

      @RequestMapping(value="/upload")
      public String uploadDocument(@RequestParam("docName)String documentName,
                                  @RequestParam("docFile")MultipartFile file)
      {
         <upload logic>

     }
       

}

The members docBase,appEnv & docPath will be initialized when the Controller instance gets created. Here doc_Base,app_Env & doc_Path are property names defined in CONFIG_KEY & their corresponding values in CONFIG_VALUE will be used for initialization

CONFIG_KEY       CONFIG_VALUE
doc_Base              test
app_Env               Dev
doc_Path              /dev/reviews



References

http://forum.spring.io/forum/spring-projects/container/82142-propertyplaceholderconfigurer-problems