Showing posts with label properties. Show all posts
Showing posts with label properties. Show all posts

Tuesday, 23 August 2011

Writing to a properties file with Ant

I find this useful when I want to change how the application works depending on where and why it is being deployed. This blog post assumes you have Ant installed!

In the build.xml file;

<!-- Add the property file -->
<property file="project.properties"/>

<!--  Write a property to the file with a value based on the target -->
<target name="liveExample">
     <echo message="This target example has the live properties"/>
     <propertyfile
          file="project.properties"
          comment="Setting important system procedure variable to 100">
          <entry key="importantVariable" value="100"/>
          </propertyfile>
</target>

<target name="testExample">
     <echo message="This target example has the test properties"/>
     <propertyfile
          file="project.properties"
          comment="Setting important system procedure variable to 10 for testing purposes">
          <entry key="importantVariable" value="10"/>
          </propertyfile>
</target>

How it works

The properties file (project.properties) has a key/value pair written to it. Based on what target is run, the key has a different value. This allows us to control how the application works based on how we deploy it. For further reading on Ant's PropertyFile task see their manual.

Wednesday, 3 August 2011

Using ResourceBundle

I use ResourceBundles to hold my project's properties so that I can make widespread changes to the project by changing only one value.

Examples of what I may use this for could be the project name, email address, directory structures etc. I would not use ResourceBundlesfor constants.

Below is a code example;

File: project.properties
projectName=AnExampleProject

File: Properties.java
package example.properties;
import java.util.ResourceBundle;

public class Properties {
  
   private static ResourceBundle rb = ResourceBundle.getBundle("example.properties.project");

   public static String getProjectName() {
     return rb.getString("projectName");
   }
}

How it works

All properties are put into a .properties file which can be retrieved using ResourceBundle's API. We get a ResourceBundle object by using the ResourceBundle method getBundle, using the path to the properties file as a parameter. With that object, we can then retrieve the properties using the getString method (other types are also available e.g. getInt).

The methods are made static so the properties can be retrieved without instantiating the Properties class every time.

The project name would be retrieved using Properties.getProjectName();