Spring Property ConfigurationSpring applications use the PropertyPlaceholderConfigurer to load application properties. Property files are typically loaded from the class path but the example below uses a slightly different approach, loading the properties file from a directory outside of the application itself. This allows the property file to be set-up and managed anywhere on the sever and most importantly, outside of the WAR or JAR file.
Lines 5 to 10 - locations attribute specifies where the properties file should be read from. In this instance we use a JVM argument to specify a properties file on the file system. We'll look at how the JVM argument is set later.
Line 11 - ignoreResourcesNotFound attribute is set to false so that a runtime exception is thrown on application start-up if the specified resource is not found. Its better to know at start-up that the resource is missing or the directory has been incorrectly configured, than finding out at runtime.
Line 12 - ignoreUnResolvablePlaceholders attribute is set to false so that a runtime exception is thrown on application start-up if a property referenced in the Spring configuration is not present in the property files. Again it's better to know at start-up that a property hasn't been configured, than finding out at runtime.
Line 13 - order attribute is set to 1 and indicates the order in which this PropertyPlaceholderConfigurer should be loaded if there are multiple instances in the application context.
Setting JVM ArgumentNext we need to set a custom JVM argument called applicationProperties - this is used in the PropertyPlaceholderConfigurer above to reference the properties file. On Tomcat we can do this by creating a file called setenv.sh in the $TOMCAT_HOME/bin directory. The values in this file will be loaded on container start up and will supplement or override JVM arguments defined in catalina.sh. We set the property file location in setenv.sh as follows.
Externalising Container Managed ResourcesNow that we've externalised our application properties we'll need to externalise container managed resources, in this example a JDBC data source. We don't want environment specific database connection details set in the application context.xml file as we'd have to rebuild and redeploy our WAR file for each environment. Instead of having this configuration defined within the application we want to externalise the resource configuration to the container.
The context.xml file contains a resource link to our JDBC data source definition as follows.
Next we update Server.xml in var/lib/Tomcat7/conf . Inside the GlobalNamingResources element we define our container managed JDBC resource. Its important that we use the same name that was used to reference the data source from the RersourceLink in context.xml above.
That's pretty much it. We've now externalised the Spring application properties and container managed resources so that our application is completely decoupled from its configuration.