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.

 

 

2 thoughts on “Web application reading configuration files

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s