can I specify a maven project.artifactId at runtim

2019-06-18 14:50发布

问题:

I have a maven POM that I'd like to use as a template, producing artifacts with different names depending on what arguments I pass to it. But I can't figure out how to specify the artifactId at runtime.

If I parameterize the <artifactId> element like this:

<artifact>foo-${bar}</artifact>

maven complains:

[WARNING] 'artifactId' contains an expression but should be a constant.

If I leave out <artifactId> in the POM and try to specify it on the command line with

mvn -Dproject.artifactId=foo ...

maven complains:

[ERROR] 'artifactId' is missing.

Is there another trick I could use to accomplish this, other than resorting to generating the POM file on-the-fly from a template? [Hmm, maybe I could do that using maven resource filtering...]

回答1:

If I get it right you want to reuse a blueprint maven application and be able to change the artifactId.

This use case can be best accomplished with Maven archetypes. See this to get you started. It's fairly straight forward and its worth learning. You have your normal Maven project and you add variables like ${groupId} in your blueprint pom. They then get replaced by parameters given by you at the archetype generation:

mvn archetype:generate                                  \
-DarchetypeGroupId=<archetype-groupId>                \
-DarchetypeArtifactId=<archetype-artifactId>          \
-DarchetypeVersion=<archetype-version>                \
-DgroupId=<my.groupid>                                \
-DartifactId=<my-artifactId>

There are also a lot of archetypes created by people on GitHub where you can learn more about structuring and filtering in Maven archetypes For example.

Alternatively you can try to set up the Maven filtering without using the archetype system but I have no experience with that. I don't think you can run a project without it having a valid artifactId, some generation must happen before that (like in generating from an archetype) but I'm not sure.



回答2:

You are going against a maven principle which is that a pom supposedly represents a self contained project generating a stable artifact (i.e. avoid parametric builds that cannot be reproduced easily).

If that's really what you want, I would use maven-install-plugin as a lifecycle step (and specifically install-file) and parameterized that rather than try to parameterize the artifactId of the pom itself.



标签: maven maven-3