Can I convert an artifactId to a classname prefix in my maven archetype?

自闭症网瘾萝莉.ら 提交于 2019-12-03 23:35:21
anttix

There is no access to arbitrary java classes from Velocity, but you can call methods of existing objects. In the context of Maven archetype you can use methods from java.lang.String and a Velocity loop to get the job done.

#macro( ccase $str )
#foreach( $word in $str.split('-') )$word.substring(0,1).toUpperCase()$word.substring(1)#end
#end
#set( $classNamePrefix = "#ccase( $artifactId )" )

public class ${classNamePrefix}Application {
    // ...
}

If you are using a fileSet tag, add filtered="true" property to make sure source files are processed with Velocity.

See also:

There's updated documentation for version 2.0: http://velocity.apache.org/engine/2.0/user-guide.html#loops

I wanted to be able to do this in file names, so I came up with a hack for a camel case artifactId property:

<requiredProperty key="artifactIdCamelCase">
  <defaultValue>${artifactId.replaceAll("^a|-a", "A").replaceAll("^b|-b", "B").replaceAll("^c|-c", "C").replaceAll("^d|-d", "D").replaceAll("^e|-e", "E").replaceAll("^f|-f", "F").replaceAll("^g|-g", "G").replaceAll("^h|-h", "H").replaceAll("^i|-i", "I").replaceAll("^j|-j", "J").replaceAll("^k|-k", "K").replaceAll("^l|-l", "L").replaceAll("^m|-m", "M").replaceAll("^n|-n", "N").replaceAll("^o|-o", "O").replaceAll("^p|-p", "P").replaceAll("^q|-q", "Q").replaceAll("^r|-r", "R").replaceAll("^s|-s", "S").replaceAll("^t|-t", "T").replaceAll("^u|-u", "U").replaceAll("^v|-v", "V").replaceAll("^w|-w", "W").replaceAll("^x|-x", "X").replaceAll("^y|-y", "Y").replaceAll("^z|-z", "Z")}</defaultValue>
</requiredProperty>

That will convert any artifactId that follows the naming convention of hyphenated, lower case a-z to camel case. From some limited testing, the format is fragile so small edits such as line breaks and regex additions may stop Velocity from replacing the property.

Should work on Maven versions after 2.1 (when this bug was fixed). My version:

> mvn -v
Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T11:29:23-06:00)

Also here is a sometimes-useful, unhyphenated version of artifactId:

<requiredProperty key="artifactIdUnhyphenated">
  <defaultValue>${artifactId.replace("-","")}</defaultValue>
</requiredProperty>

To variabilize your file name, you can set a requiredProperty and use other properties to build it

<requiredProperty key="routeBuilderFileName"><defaultValue>RouteBuilder${flowName.toUpperCase()}${flowWay.substring(0,1).toUpperCase()}${flowWay.substring(1)}</defaultValue></requiredProperty>

Then name the template file : __routeBuilderFileName__.java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!