Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

external config based on context path

Tags:

spring

tomcat

I would like to deploy multiple independent copies of a particular web-app on the same tomcat server under different context paths. Each web-app will need different configuration settings (database name, password, etc), but I would like to keep the wars exactly identical.

My plan was to have the app figure out its context path on startup, then read a specific .properties file outside of tomcat identified by the context path. For example, if a war was deployed to {tomcat path}/webapps/pineapple, then I would want to read /config/pineapple.properties

I've been trying to find a way to inject an instance of ServletContext via spring (3), but all the advice I've seen so far use the deprecated ServletContextFactoryBean.

Is there a better way to get the context path injected or better way to load external files based on the context path?

like image 895
Keith Avatar asked Dec 29 '22 04:12

Keith


1 Answers

With the help of ServletContextAttributeFactoryBean and Spring EL, you can reference ServletContext init parameters (<context-param> in web.xml) like that:

#{contextAttributes.myKey}

This allows you to use PropertyPlaceHolderConfigurer and load property files from arbitrary, user-defined locations:

<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="#{contextParameters.APP_HOME}/conf/app.properties"/>
</bean>

The corresponding definition of the ServletContext init parameter in Tomcat's context.xml:

<Parameter name="APP_HOME" value="file:/test" override="false"/>

Or in your app's web.xml:

<context-param>
    <param-name>APP_HOME</param-name>
    <param-value>file:/test</param-value>
</context-param> 
like image 85
anonymous Avatar answered Dec 31 '22 12:12

anonymous