Friday, March 16, 2012

Configuring Spring with ServletContextPropertyPlaceholderConfigurer

I came across the situation where I needed to wire my data source from a Tomcat server vs sticking the connection information within the app in a .properties file. It turns out Spring has you covered with ServletContextPropertyPlaceholderConfigurer. All you need to do is add the bean definition to your spring configuration files:

<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">

And then you add parameters to Tomcat's context.xml file :

<Parameter name="jdbc.driverClassName" value="className" override="false"/>
<Parameter name="jdbc.url" value="url" override="false"/>
<Parameter name="jdbc.username" value="username" override="false"/>
<Parameter name="jdbc.password" value="password" override="false"/>

Now Spring will find these and replace your values in your data source:

<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.username}"/>
        <property name="password" value="${jdbc.password}"/>
</bean>

No comments:

Post a Comment