我可以将artifactId转换为myven原型中的classname前缀吗?

问题描述 投票:14回答:3

我正在创建一个maven原型,并且在项目中生成了一个想要一个以生成项目的工件ID命名的类。

工件ID的格式如下:the-project-name,该类应命名为TheProjectNameMain

我试图在我的archetype-metadata.xml中做到这一点,但我无法做对。

<archetype-descriptor>
    <requiredProperties>
        <requiredProperty key="classNamePrefix">
            <defaultValue>${WordUtils.capitalize(artifactId.replaceAll("-", " ")).replaceAll(" ", "")}</defaultValue>
        </requiredProperty>        
    </requiredProperties>
</archetype-descriptor>

正如你所看到我试图使用WordUtils(来自apache-commons),但我猜这是不可用的,因为我收到了一个错误。 Error merging velocity templates:....。我也尝试了.replaceAll的不同组合,但我无法得到正确的格式。

有没有人知道在这种情况下从连字符串转换为CamelCase类名的方法?

java maven velocity maven-archetype
3个回答
19
投票

Velocity无法访问任意java类,但您可以调用现有对象的方法。在Maven原型的上下文中,您可以使用java.lang.String和Velocity循环中的方法来完成工作。

#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 {
    // ...
}

如果您使用的是fileSet标记,请添加filtered="true"属性以确保使用Velocity处理源文件。

也可以看看:

有版本2.0的更新文档:http://velocity.apache.org/engine/2.0/user-guide.html#loops


8
投票

我希望能够在文件名中执行此操作,因此我想出了一个针对驼峰案例artifactId属性的黑客攻击:

<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>

这将转换任何遵循连字,小写artifactId命名惯例的a-z到骆驼案。从一些有限的测试中,格式是脆弱的,因此诸如换行符和正则表达式添加之类的小编辑可能会阻止Velocity替换属性。

应该在2.1之后的Maven版本上工作(当this bug被修复时)。我的版本:

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

这里还有一个有时候有用的,没有连字符的artifactId版本:

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

2
投票

要变量文件名,可以设置requiredProperty并使用其他属性来构建它

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

然后命名模板文件:__routeBuilderFileName__.java

© www.soinside.com 2019 - 2024. All rights reserved.