Sunday, May 25, 2008

Create a classpath dynamically

In order to create a classpath dynamically, containing all jars in a certain directory lib, from within a batch file (Windows), just do the following:

  1. Create a cpAppend.bat file, just containing:

    set CLASSPATH=%CLASSPATH%;%1


  2. In the runnable batch file, add the following to construct the path dynamically:

    set CLASSPATH=
    for %%i in (lib\*.jar) do call cpappend.bat %%i


    The variable CLASSPATH will now contain all jars in the lib dir

That's it! On Linux/Unix the method is very similar.

Avoid absolute path in log4j properties file

In order to avoid an absolute path in a log4j.properties file (and hence to be able to add a standard log4j.properties to a cvs), just do the following:

  1. Use a placeholder in the properties file when you indicate the appender file, for instance

    log4j.appender.file.File=${log4j.logFile}


  2. Pass this placeholder value as a VM parameter to the (web) application. The log4j engine will try to resolve the placeholder and eventually fall back on the System parameters, therefore, in our example:

    ... -Dlog4j.logFile=C:/logs/MyApplication.log ...


Easy and perfectly functional!

Wednesday, May 14, 2008

Use Spring's PropertyPlaceholderConfigurer

If you define a datasource within Spring's applicationContext.xml, and don't want to put the db's parameters hardcoded into the file, but have them read from an external configuration file, you can use Spring's PropertyPlaceholderConfigurer


<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="file:${jdbc.configuration}"/>
</bean>

<!-- Datasource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>


and set the "jdbc.configuration" parameter as a VM parameter. When the propertyResolver doesn't find an existing property, it tries to fallback on the VM's system parameters, and this is just what we need.
Only the external configuration file contains the actual jdbc values, while applicationContext.xml doesn't contain any hardcoded data. Very smooth and clean!