Pagina's

zondag 3 november 2013

Using war class dependencies in Maven

Sometimes it is necessary to use classes from a Maven war project in another project. The dependent project therefore needs a dependency upon the war project. This sounds easy but including a war dependency like in the following example is not going to work:

<dependency>
    <groupId>example</groupId>
    <artifactId>exampleWeb</artifactId>
    <version>1.0</version>
    <type>war</type>
 </dependency>


In a Maven project you simply cannot use classes directly from a war dependency because they won't be added to the Maven classpath. Of course, there are many (complicated) ways to get around this but there is also an easy and clean way to get this working.

The solution lies within the Maven project in which the war file is created. This war file is created by the Maven war plugin. This plugin can be configured to create an additional artifact that contains the classes of the project. So the build will result in both a war file and a jar file.
In order to do this, configure the war plugin as follows:

<build>
    <plugins>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <attachClasses>true</attachClasses>
            </configuration>
        </plugin>
    </plugins>
</build> 


The attachClasses configuration parameter will result in the extra classes jar. Note that this classes jar will contain a classifier in its name. By default, this classifier is 'classes'. This means that the resulting name will for example be: example.exampleWeb-1.0-classes.jar. Instead of 'attachClasses' you can also use the 'archiveClasses' parameter. When using archiveClasses, the Maven war plugin will put all classes in the separate jar file instead of in the war file.

Now in the dependent project you can use the generated jarfile by using a dependency like:
<dependency>
    <groupId>example</groupId>
    <artifactId>exampleWeb</artifactId>
    <version>1.0</version>
    <classifier>classes</classifier>
</dependency>


So this is an easy way to get a dependency upon the classes from a war project.
In case you don't like the default classifier 'classes', you can change it into something else by using the war plugin configuration parameter 'classesClassifier'.

Geen opmerkingen:

Een reactie posten