views:

528

answers:

3

Hi, I wanted to substitute the placeholder dynamically in properties in a java application. Like

 WelcomeMessage=Welcome Mr. {firstName} {lastName} !!!

These firstName and LastName variable needs to be substituted dynamically. Should we use velocity template engine for the same? Or are there any other opensource frameworks for the same?

Thanks, Manish

A: 

velocity is the best tool as of now. But it depends on what file type you want to use as a template.

For example, if you want to use MS word docs as template, then you have to extend velocity classess and write your own implementation.

Joseph Kulandai
+1  A: 

You can use the MessageFormat class of Java SE. It allows you to do exactly what you ask for.

In your case the below code snippet must do the trick, assuming props contains all the properties loaded from your file.

MessageFormat.format((String) props.get("WelcomeMessage"), "First", "Last");

Note that your properties files should have index of parameters instead of named parameters as below.

WelcomeMessage=Welcome Mr. {0} {1} !!!
Chandru
It does, yes, except that inexplicably, it's defined using numeric placeholders rather than meaningful symbolic ones. Amazing how much harder that is to use.
T.J. Crowder
Edited my reply just as you were commenting. :)
Chandru
+1  A: 

Velocity is rather old and unpleasant, in my opinion, there are nicer ways to do this:

  • StringTemplate is the simplest of the template engines, and good enough for what you need (see syntax examples here).
  • If you're already using Spring 3, it has the PropertyPlaceholderHelper class which can do this also, but I wouldn't use Spring just to get hold of this one class.
skaffman