Web application reading configuration files

Almost all applications running in some web container need access to some configuration file. I always wondered what was the best path and approach to refer it with in your application so you don’t need to worry a lot like redeploying application, rebuild just for changing the configuration file path.

This example assumes it’s a spring web application (however the approach should still work even if it’s not a Spring project just refer to the propertiesLocation env-entry defined in web.xml in your Java code 🙁 haven’t tested though !) here is how the application-context file looks like.

<beans>
<context:property-placeholder location="${propertiesLocation}" />
<!--Specific Context file imports-->
<import resource="classpath:/META-INF/main-context.xml"/> 
</beans>

Now add the following environment entry into web.xml file.

<env-entry>
<env-entry-name>propertiesLocation</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type> 
</env-entry>

Now add the following to you web server configuration xml file

For jetty: (the propertiese file will be picked up from src/main/resources/app.properties) good for running locally 🙂

<New id="propertiesLocation" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>propertiesLocation</Arg>
<Arg>file:src/main/resources/app.properties</Arg>
</New>

For tomcat: (the propertiese file will be picked up from opt/projectname/tomcat7/conf/app.properties)

Add to TOMCAT_HOME/tomcat7/conf/context.xml:

<Parameter name="propertiesLocation" value="file:///opt/projectname/tomcat7/conf/app.properties" override="true"/>

Great we are done now and can refer to properties file location without messing with directory paths.

About: Muhammad Ali

I am a Java and Tibco expert. I have Master's degree in software engineering of distributed systems from Royal Institute of technology KTH Stockholm Sweden and I am an expert software engineer and integrator with over a decade of industry experience from Europe, Gulf and Asia regions. I am a strong opensource believer and encourage "sharing as caring" principle.


2 thoughts on “Web application reading configuration files”

Comments are closed.