英文:
Gradle build jar cannot find dependency at run time
问题
以下是您的翻译内容:
我在下面的 build.gradle 文件中引入了 json-simple 依赖:
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
testImplementation('org.junit.jupiter:junit-jupiter-api:5.4.2')
testRuntime('org.junit.jupiter:junit-jupiter-engine:5.4.2')
compile 'com.googlecode.json-simple:json-simple:1.1.1'
}
test {
useJUnitPlatform()
}
jar {
manifest {
attributes(
'Main-Class': 'src.main.java.demo.Hello'
)
}
}
我有以下使用 json-simple 的类:
package src.main.java.demo;
import org.json.simple.parser.JSONParser;
import org.json.simple.JSONObject;
public class Hello {
public String hello() {
try {
String jsonString = "{\"first\":\"Hello\",\"second\":\"world\"}";
JSONParser jspa = new JSONParser();
JSONObject job = (JSONObject) jspa.parse(jsonString);
return (String) job.get("first");
} catch (Exception e) {
return "";
}
}
public static void main(String[] args) {
System.out.println(new Hello().hello());
}
}
项目成功构建,但在运行创建的项目 jar 文件时,它显示找不到 "JSONParser" 和 "JSONObject"。这意味着这些依赖项在运行时未被添加。我应该怎么做才能将它们添加到类路径中?
谢谢!
英文:
I have below build.gradle file in which I have included json-simple dependency:
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
testImplementation('org.junit.jupiter:junit-jupiter-api:5.4.2')
testRuntime('org.junit.jupiter:junit-jupiter-engine:5.4.2')
compile 'com.googlecode.json-simple:json-simple:1.1.1'
}
test {
useJUnitPlatform()
}
jar {
manifest {
attributes(
'Main-Class': 'src.main.java.demo.Hello'
)
}
}
I have below class which uses json-simple:
package src.main.java.demo;
import org.json.simple.parser.JSONParser;
import org.json.simple.JSONObject;
public class Hello{
public String hello(){
try{String jsonString="{\"first\":\"Hello\",\"second\":\"world\"}";
JSONParser jspa=new JSONParser();
JSONObject job=(JSONObject)jspa.parse(jsonString);
return (String)job.get("first"); }
catch(Exception e){
return "";
}
}
public static void main(String[] args)
{
System.out.println(new Hello().hello());
}
}
The project builds successfully but on running the created jar file of project, it says it cannot find JSONParser and JSONObject
. It means that these dependencies are not added at runtime. What should I do to add them to the classpath?
Thank You!
答案1
得分: 3
你应该创建一个可执行的JAR文件。请按以下方式更改你的Gradle构建文件:
对于较新版本的Gradle,使用以下代码:
jar {
manifest {
attributes 'Main-Class': 'src.main.java.demo.Hello'
}
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
对于较旧版本的Gradle,使用以下代码:
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
英文:
You should create a fat jar. Change your build gradle like this
jar {
manifest {
attributes "Main-Class": "src.main.java.demo.Hello"
}
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it)}
}
}
for older Gradle you should use this
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论