无法运行jar文件(Maven项目)



我是Maven的新手。我创建了Maven项目并安装了它(构建成功),但我不能从命令提示符下运行jar文件,它说

错误:无法访问jarfile

我想我在POM文件中有错误

<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ru.nick.kru</groupId>
    <artifactId>ParagonCase</artifactId>
    <version>1.1</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>Main</mainClass>
                            <packageName>ru.nick.kru</packageName>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>
</project>

用Maven构建一个可执行的Jar文件可能很棘手,但有一种方法可以做到!看起来你走在了正确的轨道上,但可能在插件的"packageName"属性中缺少"ParagonCase"(如果你的Main函数是ru.nick.kru.ParagonCase.Main,那么你的packageName应该是ru.nik.kru.PalagonCase)。

我还发现使用maven shade插件很有用,它将所有必要的依赖项捆绑在Jar中(即,当运行Jar时,您不需要将所有这些依赖项作为类路径中的独立Jar)。

在您的POM中,您可以添加以下构建插件:

<build>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>2.3</version>
    <executions>
      <!-- Run shade goal on package phase -->
      <execution>
        <phase>package</phase>
        <goals>
          <goal>shade</goal>
        </goals>
        <configuration>
          <transformers>
            <!-- add Main-Class to manifest file -->
            <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
              <mainClass>ru.nick.kru.ParagonCase.Main</mainClass>
            </transformer>
          </transformers>
        </configuration>
      </execution>
    </executions>
</plugin>
</build>

为了运行Jar(在使用mvn package创建之后)。用java:启动它

java -jar ParagonCase.jar

最新更新