djeikyb
djeikyb

Reputation: 4598

How to use maven to generate code and package it without dependencies?

I have a project that generates some classes and resources that should then be packaged into a jar.

The class that does the generating has several dependencies. The generated classes have no dependencies.

My initial solution was to use the maven assembly plugin to only include the generated files. Unfortunately, the packaged pom includes all the dependencies required to do the generation. Consumers of this jar pull in a bunch of unnecessary dependencies.

I looked into the maven shade plugin. I compile once, run the generator class with mojo's exec plugin, the compile a final time. Then shade of course runs in the package phase. It creates a dependency-reduced-pom.xml without the excessive dependencies. So run mvn clean package and look in target/foo.jar. I expect the jar in the meta-inf folder to be the reduced dependency jar. But it's the full pom. I don't know how have the generated pom replace the one that is packaged.

Another poor solution I tried was using multiple profiles with their own dependency section. I run maven once with the generating profile, then again with the packaging profile. This works, but sucks because you have to run multiple maven commands. It's not jenkins friendly.

Am I going about this the wrong way? How should I go about arranging a project that generates some code and some text files that are then packaged in a maven friendly artifact?

Upvotes: 1

Views: 1783

Answers (1)

Daniel Sperry
Daniel Sperry

Reputation: 4491

1) One possibility is to make all your dependencies <optional>true</optional>.

The pom will still have the dependencies but the projects using your library won't try to download them.

2) Use plugin dependencies with the exec plugin.

That works well if the generator class is defined on another project.

Ideally you would call your generator using a plugin and avoid adding those dependencies to your project. That may not be worth doing depending on what your project is for and how reusable your generator has to be.

3) If you are using maven-shade-plugin the dependency-reduced-pom.xml is normally used. Check your .m2 repository to see the contents of the pom that is copied there when you do mvn install. It's likely that its contents will match the dependency-reduced-pom.xml

Upvotes: 1

Related Questions