Tuesday, May 1, 2012

Maven 3: Default Values for Mojo Parameters that are Collections

I love my custom Maven mojos (or plugins). However, I recently ran into a situation where I needed a parameter that was a list of archive types (zip, tar, etc.), and I wanted to specify some reasonable default. Have you ever tried this by specifying a default-value or an expression? After searching for about an hour, I have come to the conclusion that the designers of Maven didn't thing this through all the way.

Not to fear though! There is a way to get this to work, and I like it so much I think I will start using the "hack" in preference to the "right way."

The trick is to specify a default value for the variable in Java. Don't use default-value or expression at all. If the user doesn't override the value, the variable doesn't get set, so it just picks up the default value you've assigned.

The second part of the trick is to document your default settings in the JavaDoc. Since you aren't specifying the value as part of the @parameter annotation, the site-doc report and help won't pick up the value you've assigned.

Here is an example.

/**
 * Types of archives to create. Any of <code>zip</code>, 
 * <code>tar</code>, <code>tar.gz</code>, <code>tar.bz2</code>.
 * <br><strong>Default</strong>: <tt>["zip", "tar.gz"]</tt>
 * @parameter 
 */
protected List<String> types = Arrays.asList("zip", "tar.gz");

One thing to note is that this will only work for constants. Any default values that have to be pulled from the project context (such as project file paths) are going to require an expression. This can't be helped. Those values have to be injected after the plugin is constructed.

No comments:

Post a Comment