Maven by Example
   - 4.7. Add Resources

4.7. Add Resources

This project depends on two classpath resources: the Main class that configures Log4J with a classpath resource named log4j.properties, and the WeatherFormatter that references a Velocity template from the classpath named output.vm. Both of these resources need to be in the default package (or the root of the classpath).

To add these resources, we’ll need to create a new directory from the base directory of the project: src/main/resources. Since this directory was not created by the archetype:generate task, we need to create it by executing the following commands from the project’s base directory:

$ cd src/main
$ mkdir resources
$ cd resources

Once the resources directory is created, we can add the two resources. First, add the log4j.properties file in the resources directory, as shown in Simple Weather’s Log4J Configuration File.

Simple Weather’s Log4J Configuration File. 

# Set root category priority to INFO and its only appender to CONSOLE.
log4j.rootCategory=INFO, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=INFO
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r %-5p %c{1} %x - %m%n

This log4j.properties file simply configures Log4J to print all log messages to standard output using a PatternLayout. Lastly, we need to create the output.vm, which is the Velocity template used to render the output of this command-line program. Create output.vm in the resources directory.

Simple Weather’s Output Velocity Template. 

*********************************
Current Weather Conditions for:
${weather.city}, ${weather.region}, ${weather.country}

Temperature: ${weather.temp}
Condition: ${weather.condition}
Humidity: ${weather.humidity}
Wind Chill: ${weather.chill}
*********************************

This template contains a number of references to a variable named weather, which is the Weather bean that was passed to the WeatherFormatter. The ${weather.temp} syntax is shorthand for retrieving and displaying the value of the temp bean property. Now that we have all of our project’s code in the right place, we can use Maven to run the example.












Become a Member

Are you a current user of:

Top