Deployment – Spring – Overriding properties when deploying in a multi-server environment

I found myself wanting to have certain property values in my Spring projects differ based on what server the app is being deployed.

For example your company has dev, test, qa, prod boxes etc… But there are certain properties in your app such as default db username and passwords, database name, thread pool configurations, etc… that are specific to the server or environment where the app is running.

The technique presented in this tutorial allows you to place all common and default properties in a properties file and provide overrides based on the hostname of the server where the app is running.

For example you can have a application.myDevBoxHostName.properties that will allow you to load property values associated to your own local environment versus a application.myCompany.com.properties that will load the right set of properties in production servers. Also you can have simply application.properties to load all properties that are common or with default values for all environments that do not override properties

This tutorial is available for download with svn:

svn checkout http://raulrajatutorials.googlecode.com/svn/trunk/ raulrajatutorials-read-only

Comments in the code itself should be self-explanatory if you already have some java + spring experience

And now to the point.

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <!--
    This service allows loading of properties based on hostname supporting default values in application.properties and allowing
    other servers to override the default property values in their own server specific application._HOST_NAME_.properties
    -->
    <bean id="applicationProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesMode" value="1"/>
        <property name="locations">
            <list>
                <value>/WEB-INF/conf/application.properties</value>
                <!--
                    In deployments servers: /WEB-INF/conf/application._HOST_NAME_.properties will override properties in application.properties.
                    based on the hostname in the deployed server
                -->
                <bean class="com.raulraja.util.deployment.CompositeStringResourceProvider" factory-method="getReplacedResource">
                    <constructor-arg>
                        <bean class="com.raulraja.util.deployment.impl.SpringInjectedServletContextProviderImpl" />
                    </constructor-arg>
                    <constructor-arg value="/WEB-INF/conf/application._HOST_NAME_.properties"/>
                </bean>
            </list>
        </property>
        <property name="ignoreResourceNotFound" value="true"/>
    </bean>
 
    <!-- This is a sample service that will get properties injected and will display its values on initialization -->
    <bean id="sampleService" class="com.raulraja.util.deployment.impl.SampleServiceImpl" init-method="init">
        <property name="firstProperty" value="${first.property.placeholder}" />
        <property name="secondProperty" value="${second.property.placeholder}" />
    </bean>
 
</beans>

application.properties

#In this file live all common properties and default property values for all servers
first.property.placeholder=this value was declared in application.properties
second.property.placeholder=this value was declared in application.properties

application.yourHostNameHere.properties

# This file contains properties overriden for the host name were the app is being deployed
second.property.placeholder=this value is overriden in a specific server config declared in application.properties

CompositeStringResourceProvider.java

package com.raulraja.util.deployment;
 
import org.apache.log4j.Logger;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.context.support.ServletContextResource;
 
import java.net.UnknownHostException;
import java.net.InetAddress;
 
/**
 * A service that provides a resource based on the host name
 */
public class CompositeStringResourceProvider {
 
    private final static Logger log = Logger.getLogger(CompositeStringResourceProvider.class);
 
    private final static String HOSTNAME_PLACEHOLDER = "_HOST_NAME_";
 
	/**
	 * This method is invoked by the container at startup
	 * @param servletContextProvider a servlet context provider
	 * @param baseResource the base resource
	 * @return the resource assigned to the current running server
	 * @throws UnknownHostException if the host is unknown
	 */
    public static Resource getReplacedResource(ServletContextProvider servletContextProvider, String baseResource) throws UnknownHostException {
        InetAddress localhost = InetAddress.getLocalHost();
        baseResource = baseResource.replaceAll(HOSTNAME_PLACEHOLDER, localhost.getHostName());
        Resource resource = null;
        if (servletContextProvider.getServletContext() != null) {
            resource = new ServletContextResource(servletContextProvider.getServletContext(), baseResource);
            if (resource.exists()) {
                log.debug("Loading override for common properties: " + resource.getFilename());
            }
        } else {
            resource = new ClassPathResource(baseResource);
        }
 
        return resource;
    }
 
}

ServletContextProvider.java

package com.raulraja.util.deployment;
 
import javax.servlet.ServletContext;
 
/**
 * Provides a servlet context
 */
public interface ServletContextProvider {
 
	/**
	 * @return the servlet context
	 */
    ServletContext getServletContext();
 
}

SpringInjectedServletContextProviderImpl.java

package com.raulraja.util.deployment.impl;
 
 
import com.raulraja.util.deployment.ServletContextProvider;
import org.springframework.web.context.ServletContextAware;
 
import javax.servlet.ServletContext;
 
/**
 * Spring based impl of the ServletContextProvider
 */
public class SpringInjectedServletContextProviderImpl implements ServletContextProvider, ServletContextAware {
 
	/**
	 * the servlet context
	 */
    private ServletContext servletContext;
 
	/**
	 * @return the servlet context
	 */
    public ServletContext getServletContext() {
        return servletContext;
    }
 
	/**
	 * sets the servlet context, invoked by the container at startup since this service implements ServletContextAware 
	 * @param servletContext the servlet context
	 */
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}

SampleServiceImpl.java

package com.raulraja.util.deployment.impl;
 
import org.apache.log4j.Logger;
 
/**
 * Demonstrates how values of properties are injected based on a specific hostname config
 */
public class SampleServiceImpl {
 
	private final static Logger log = Logger.getLogger(SampleServiceImpl.class);
 
	/**
	 * the first prperty
	 */
	private String firstProperty;
 
	/**
	 * the second property
	 */
	private String secondProperty;
 
	/**
	 * service initialization method
	 */
	public void init() {
		log.debug("first property: " + firstProperty);
		log.debug("second property: " + secondProperty);
	}
 
	/**
	 * sets the first property
	 * @param firstProperty the first property
	 */
	public void setFirstProperty(String firstProperty) {
		this.firstProperty = firstProperty;
	}
 
	/**
	 * sets the second property
	 * @param secondProperty the second property
	 */
	public void setSecondProperty(String secondProperty) {
		this.secondProperty = secondProperty;
	}
}

Now notice that my local machine hostname is raul-raja-martinezs-macbook.local

Before application.raul-raja-martinezs-macbook.local.properties existed:

06/13 17:49:52 WARN org.springframework.beans.factory.config.PropertyPlaceholderConfigurer – Could not load properties from ServletContext resource [/WEB-INF/conf/application.raul-raja-martinezs-macbook.local.properties]: Could not open ServletContext resource [/WEB-INF/conf/application.raul-raja-martinezs-macbook.local.properties]
06/13 18:00:47 DEBUG com.raulraja.util.deployment.impl.SampleServiceImpl – first property: this value was declared in application.properties
06/13 18:00:47 DEBUG com.raulraja.util.deployment.impl.SampleServiceImpl - second property: this value was declared in application.properties

After application.raul-raja-martinezs-macbook.local.properties existed:

06/13 18:03:52 DEBUG com.raulraja.util.deployment.CompositeStringResourceProvider – Loading override for common properties: application.raul-raja-martinezs-macbook.local.properties
06/13 18:03:52 DEBUG com.raulraja.util.deployment.impl.SampleServiceImpl – first property: this value was declared in application.properties
06/13 18:03:52 DEBUG com.raulraja.util.deployment.impl.SampleServiceImpl – second property: this value is overriden in a specific server config declared in application.properties

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • MySpace
  • RSS
  • TwitThis
  • email
  • FriendFeed
  • PDF
  • Slashdot

This post is tagged , ,

don't '

Leave a Reply

Comments may be held for moderation, please do not repost. I reserve the right to remove any inappropriate or off-topic comments. If you plan on sharing helpful code, please pass it through Postable first. Want other to know who you are? Register a Gravatar.





Sponsored Links

Categories

Pages

glactic siv ii dark gamespot
huraikan kebaikan mempelajari seni dalam pendidikan
12 cell embryo transfer
apple morphine
driving nextel tractor trailers
at t gprs settings p168
himalayan cat history
baby sister birth announcement
bausch lomb metallograph
adapter hose bib to air compressor
download marvel vs capcom dreamcast
rodger cravens
exercises to relieve back pain
cha behavioral health care sympsium
2pac edited
entourage ari job interview
xushobby.com
carbohydrate snacks for diabetics
prevent scarring with
canadian costal vacation cottages
patientsafetyfirst.org
automotive ic
chris brow run it
finned pack exchangers
reflexive intuition
darla godfrey motorcycle accident
1989 isuzu trooper parts
healthcare comany boca ration florida
2 pac feat biggie running
628 manitou rd se calgary ab
corvette nos parts
edwin wiley grove
build with legos
christianity framework
low morale in the wok place
room111heroes.com
raroc risk adjusted return on capital
definitions of negotiation
bobby ogden portland oregon
after death of jesus what happen
100 proof
bashlin lineman gaffs
affiliatetraction.com
adjustable pistol sight eaa witness compact
county inn suites mankato
alf episodes
lakehopestatepark.com
3ds importer for maya
darrell hensley
paragon ballroom roselle park nj
848 ardis vaughn
hirewelders.com
big pond otis
thumbspower.com
jsp advantage disadvantage
babes in tight shorts gallery
326 e main st ravenna
burgundytoday.com
7 dollar scripts
nightmare before christmas silhouettes
anthropologie promotions
coffee cupcake recipes
925e.com
a w richard sipe
european parliament empty seat 666
blueridge slots
executive director of philanthropy salary
catholic doctrine the sabbath
integrating literacy urban school
myflooring.info
corn starch extra fine corn mill
dickie dee hotdog lemonade fruit cart
edna cox
24 hr frys near 85042
sir john whitmore
phsource.us
anthony dillie midland tx
cum-eating-whores.com
1999 san antonio spurs
blazing ink tattoo shop
immanuel hospital omaha ne
arundel mills mall hanover maryland
berkeley advisors horvath
air pollution from poultry farms
cardboard display pos
canadian tire assistant vice president
tubularspices.com
russian authors views of color revolutions
amazon ca hans neleman books
code of silence
therepublicannews.com
all brands of bourbon
1957 hillman husky windshield
milestone distributors
pantera.com
autobahn melville
grosfillex fidji highback stacking
hot skeet
girls with donkeys
average persons iq
akira ghost in shell
aerial imagery free
firearms disassemble sks chinese
obstacle detection advantages disadvantages
calphalon enamel cast iron
hotdog chilli recipes
different strokes theme lyrics
lhmopars.com
airworks zephyr
bounty hunter medal detectors
clarion radio pinout
bitter tea imeem lollipop
1031 al exchange
aguilera aint no other man
annabel lee edgar allan poe analysis
apple varieties for cooking and eating
cannot search properly on google
lucy and ricky ricardo costumes
bill frazier
shana bowers
1965 ignition switch diagram
roushhonda.com
lyrics in english ricardo arjona
birth control pills and blood clots
redrival.com
ancestors of leslie tilbrook born 1902
2009 craddock forces nato
abcteachingjobs.com
1952 buick exhaust manifold
foxpro odbc
pete wentz arm
articles by linda darling hammond
138kv breaker
forster tuncurry accommodation
developed lakes and communities
alice walkr and ernest gaines
new idea uni sytem parts
justoffbase.co.uk
business case framework
.30-30 reloading data red dot
16 gage earrings
porn-mature.org
100 most useful gifts for women
2008 xterra
blue point siamese male
mc-ala.org
average dose of klonopin
atom center alaska
clifford macgregor
ccna 1 v4.0
acc 25 265
cvs 41 midway
autoimmune disease in german shepherds
stormyleather.com
how to suffer
dll files quicken
1990 mako boat
disater preparedness
boat countertop
11043 oroville hwy
dads doing there sons
animate your own 3d picture online
starry night by van gogh tile
kpmg glasgow vacancies
2004 buick rainier front tow hook
474 interstate replaces
zodiacs4u.com
baby boy christening gown
back to the future star christopher
freehdporn.net
bromelain and arterial plaque
millville pa notary public
wareztoplist.com
hyper-v vm disappear
afi teak
college footbal coach changes
bikram london west
mediaonecars.com
2007 crystal skulls update
esau milo
ancient cities in the jungle
bishop connolly
600 amps general electric ak-2a-25
1970 arctic cat panther
bon jovi only lonely
address for jennifer dean gainsville florida
gunit.com
2007 irish golf open winner
106.3 radio chatham
beautiful baby beautiful hbo elliott erwitt
cellulosic pulp
bluetick hound pups for sale
fram ancestry
ole time lyrics happy wanderer
america as a religious refugee
bette midler las vegas show
deliciousdays.com
gunz injector
currently filming on location downey ca
arlington county va register of deeds
1035 fm halifax
a bed breakfast at wisteria way
shs.net
1970 s cove heaters
artists similar to gabriella cilmi
carlos gomez slam
acdc photos for my profile
1986 honda spree piston rings
175 walnut ave santa cruz
chameleon canoes
calenders kids printable
generated credit cards
devastating earthquakes along convergent plate boundaries
bmxultra.com
angola air airway
jeffrey koontz
cell phone dealers in visalia ca
bording schools for 7th graders
1996 subaru montana
arched wrought iron lawn edging
810whb.com
70 s symbols
asc coupler
car rental in tenerife grand canaria
paintballbuster.com
choosing a computer
california houseboat rules
chanel handbag knock off
are wireless routers as good
compile macros
targus
firstsavingsbanks.com
bull shoals arkansas scuba
all freezer 14 cub
activision keygen
1950 s tool cataloug
170 80-15 spokes motorcycle tires
free shredding and bank
adalib.org
chamillionaire king knog
black tailed virus
1970 women tennis players
mujeresdesnudas.com.es
man into hawk tf
cheats for godzilla destroy all
2005 arctic cat zr 900
8 straight stem tire tubes
softwarefeast.com
algonquin flags and symbols
clear kerosene suppliers in new jersey
gisele sass
amc movie theater in humble
buttaro pottstown
sexinvideos.com
2005 nissan frontier nismo production
casted memories
20 coupon linens n things
pollenwidgets.com
cane creek headsets
all shoes with vibram soles
thecontractsite.net
8 line poems
100 free tax filing
60 mph electric motor bikes
missohiousa.com
colour tv in all rooms scarborough
corral cleaning
gainsville classified
xamps.com
horn microphones
camelot castle history
300 march to glory game download
bloke sportbike forum
average annual dew point in maine
815 west hastings
anh joseph gao
1970 buick gran sport
cheesy hash brown casserole
wakeboarding parks
fonda self
free online chevrolet service manuels
alison braun
bland kinny
britney skye pool
interior doors watford uk
cheatinfo.de
dumb and dumber suit
8.00 puerto rico tickets
because to see her lips they
dbx 386
buy raspberry pie
one-way anova with unequal sample sizes
deepest point 407 meters
dragonball-z.us
frequently asked questions about gerund
altoids licorice
macombsheriff.com
fictional children books on the holocaust
bikinis for your body type
househacker.com
archvision rpc resort free
25545 fansites
harlequin books download
lvl rafters
1993 sun tracker party barge 24
batch rename rotate mac freeware
coded welder definition
church choral music songbook
antonia feat sandra
advance reader copies hyperion teens
buddha monk
carstuckgirls.com
2005 tacoma glove compartment shock
andrew mitchell elementary
bc1.com
3d models of osmosis
air sport internationale sa geneva swiss
glens falls frive in
flogging molly salty dog
02 accord rims
guitar tanglewood tw15
airline industry s unemployment rate chart
buy a cat bolingbrook chanel 6
department of tourism government of karnataka
2005 m nchhof estate riesling
anclote river salinity
curt cattau
earthquakesound.com
2002 suzuki marauder vz800
fats and oils nutrition lesson plan
camshaft 350 chevy
2220 west chew street allentown pa
arik airline job vacancy
1403 income taxes
concrete stamping techniques
carver reciever
adaptations plants reduce water loss
2006 stanley cup playoffs
canine conception lh progesterone
gama seal lids
2113 garage door opener
adobe executive
1998 gm 14 bolt 6 lug
bobby whitaker plainview
2008 suzuki bandit gt
408a retirement account
accounting majors belleville il
create a headstone
chrono cross ntsc