Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a resource to be included in Jar file with maven?

Tags:

maven

During my build I need to some files to be generated by an external tool. For my minimal compilable example I reduced my "external tool" to the following script:

mkdir -p target/generated-resources
echo "hello world" > target/generated-resources/myResource.txt

Now I want to execute my external tool during build and the generated resource should be included in the war file. I could not find any documention on how that should be done, so it was just a guess that I need to write my generated resource to target/generated-resources. So maybe that is a problem?

I created a pom.xml file with the following build configuration:

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <executions>
                <execution>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <executable>./createResource.sh</executable>
            </configuration>
        </plugin>
    </plugins>
</build>

If I run mvn package my createResource.sh script gets executed successfully and the myResource.txt file is created. However the myResource.txt file is not included in the resulting .jar file.

I noticed that it works if I add

<resources>
  <resource>
    <directory>target/generated-resources</directory>
  </resource>
</resources>

to my build config, but I fear that this may cause problems if other plugins which may use this directory differently (Do they? I could not really find anything about the conventions of the target directory).

Additionally I'd prefer a solution that works with the usual maven conventions (if a convention for this case exists).

How do I correctly generate a resource to be included in the jar file during build using maven?

like image 467
yankee Avatar asked Sep 19 '25 01:09

yankee


1 Answers

Convention (or main usage at least)for Maven is to generate resources inside (target/generated-resources/[plugin/process]). But unlike generated sources and compiler plugin, generated resources are not handled specifically by the jar plugin, so you do have to add it as a resource (with a new resource like you did or the build-helper-plugin).

If you follow the convention to place everything you generate under a sub-directory of generated-resources, you should have no fear about how other plugins use it.

like image 180
Tome Avatar answered Sep 20 '25 15:09

Tome