Search code examples
javaspring-bootmavenmaven-pluginmaven-assembly-plugin

Maven: Generate both jar and war for the project using same pom.xml


I have a project and i need to generate both jar and war of the project using same pom.xml.
So when i run 'mvn clean install' it should generate both jar and war in my ~/m2 directory.
I needed this jar to build my second project.
Below is the sample pom.xml.

<artifactId>demo-service</artifactId>
<name>demo-service</name>
<description>service demo</description>
<packaging>war</packaging>
.
.
.
<build>
    <plugins>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.6</version>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>${start-class}</mainClass>
                    </manifest>
                </archive>
                <excludes>
                    <exclude>**/*.properties</exclude>
                    <exclude>**/*.xml</exclude>
                </excludes>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
                <execution>
                    <id>default-war</id>
                    <phase>prepare-package</phase>
                    <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <finalName>${pom.artifactId}</finalName>
                <appendAssemblyId>false</appendAssemblyId>
                <descriptor>src/main/assembly/assembly.xml</descriptor>
            </configuration>
            <executions>
                <execution>
                    <id>create-archive</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Thanks.


Solution

  • You can try options archiveClasses and attachClasses of maven-war-plugin

    So your configuration can look like:

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-war-plugin</artifactId>
      <version>3.3.2</version>
      <configuration>
        <archiveClasses>true</archiveClasses>
        <attachClasses>true</attachClasses>
      </configuration>
    </plugin>