Sunday, December 28, 2014

Properties overriding in Spring

    Encapsulation can be applied not only to classes. It can also be applied to properties but in slightly different flavor. From my standpoint encapsulation and convention over configuration are two important factors which determine the robustness of the solution.
I like to have a bunch of default properties for development purposes. I keep them in properties files which land in JARs that are eventually stored inside app.war/WEB-INF/lib. However, different properties are necessary for different environments (e.g. JDBC related properties, pool sizes, endpoint URLs, etc.). What is more, on PROD environments the properties are usually managed by different people - Operations Team. Because of that fact, I like to expose as little as possible. I start with reasonable defaults and then I allow to override some of these defaults. Let's consider the following code:
public class PropertyLoader {
 private String myProperty;
 public static void main(String[] args) {
  AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(PropertyLoader.class);
 public String getMyProperty() {
  return myProperty;
 public static PropertySourcesPlaceholderConfigurer  propertyConfig() {
  PropertySourcesPlaceholderConfigurer  propertyConfig = new PropertySourcesPlaceholderConfigurer();
  // the order of Locations is important here
  propertyConfig.setLocations(new ClassPathResource(""), 
                              new ClassPathResource(""));
  return propertyConfig;
and the following module structure:

The content of the file is: = MyDefaultValue
The result of the main method execution is:
It seems we have some default property value stored within property file. Then we can add one more property file:
with the following content: = MyOverridenValue
and the result of the main method execution is now:
It is enough that file appears in the classpath. In the distribution WAR file we have only and can be specified outside WAR file - we just need to modify the classpath. If you use Tomcat you can add to tomcat/bin/
This approach follows encapsulation (only necessary properties are exposed) and convention over configuration (reasonable default values are specified) principles.

P.S. This is the last post in 2014. Happy New Year and stay tuned for the upcoming entries in 2015!

1 comment :