Search code examples
javamavenpom.xmlpackaging

Run maven project with main() method in imported dependency in pom


Is there a way in which we import dependency in the pom for a maven project. Then when we package it and run the jar, the Main() method is provided by the dependency we imported and not in the project we are developing ourselves.

Is there a possibility of doing it? Basically, the dependency would load the project developed by me from the classpath and consume some of the interfaces implemented by me, known to it.


Solution

  • I haven't tried it, but you may be able to simply specify the main class in the manifest using maven-jar-plugin, like so:

    <project xmlns="http://maven.apache.org/POM/4.0.0" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.maventest</groupId>
        <artifactId>aproject</artifactId>
        <packaging>jar</packaging>
        <version>1.0-SNAPSHOT</version>
        <name>aproject</name>
        <url>http://maven.apache.org</url>
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-jar-plugin</artifactId>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>com.maventest.App</mainClass>
                            </manifest>
                        </archive>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>
    

    If that doesn't work you could always provide your own class that imports and calls the main method from the desired class.