我用gradle在spring框架测试代码中构建jar文件。
然后运行jar文件“ java -jar jarFile.jar” 但是它无法运行并显示一些错误代码。
我在spring项目的build.gradle文件中检查了Main-Class属性 和MANIFEST.FM文件放在jar文件中
这是我的主要课程Java代码
package com.apress.springrecipes.sequence;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.apress.springrecipes.sequence.config.SequenceConfiguration;
public class Main {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(SequenceConfiguration.class);
SequenceGenerator generator = context.getBean(SequenceGenerator.class);
System.out.println(generator.getSequence());
System.out.println(generator.getSequence());
}
}
这是我的build.gradle文件
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'
mainClassName = "com.apress.springrecipes.sequence.Main"
repositories {
mavenCentral()
}
jar {
baseName = "${rootProject.name}"
version = "0.0.1-SNAPSHOT"
manifest {
attributes "Implementation-Title": "${rootProject.name}",
"Implementation-Version": version,
"Main-Class": "${mainClassName}"
}
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
ext {
springVersion = '4.2.0.RELEASE'
}
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
dependencies {
compile "org.springframework:spring-core:${springVersion}"
compile "org.springframework:spring-context:${springVersion}"
compile "org.slf4j:slf4j-simple:1.7.25"
}
这是jar文件中的MANIFEST.FM文件
Manifest-Version: 1.0
Implementation-Title: recipe_2_2
Implementation-Version: 0.0.1-SNAPSHOT
Main-Class: com.apress.springrecipes.shop.Main
当我运行jar文件时,我收到错误消息
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContext
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: org.springframework.context.ApplicationContext
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
我该如何解决?
答案 0 :(得分:0)
gradle“应用程序”插件将在 build / distributions 中输出zip文件,因此您可以将其提取到文件夹中,该文件夹具有 bin /,lib / >
您可以像
一样运行程序bin/${rootProject.name}
请不要直接在lib中运行您的jar文件