Gradle Java和MongoDB [英] Gradle Java and MongoDB

查看:120
本文介绍了Gradle Java和MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试连接到本地MongoDB实例(版本3.2).我已经在build.gradle中指定了一个依赖项,如下所示:

I'm trying to connect to a local MongoDB instance (version 3.2). I've specified a dependency in my build.gradle like so:

依赖项{编译'org.mongodb:mongodb-driver:3.3.0'}

dependencies { compile 'org.mongodb:mongodb-driver:3.3.0' }

我有一个简单的App.java文件,其中包含以下代码(请参见下文). build/compileJava步骤运行良好,没有错误.但是,当我运行代码时,我得到:线程主"中的异常" java.lang.NoClassDefFoundError:com/mongodb/MongoClient位于App.main(App.java:9)

I have a simple App.java file with the following code (see below). The build/compileJava steps all run well with no errors. But when I run the code, I get: "Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/MongoClient at App.main(App.java:9)

我是Java的新手.我不确定除了在build.gradle依赖项列表中引用该驱动程序外是否还需要下载该驱动程序,如果需要,还应在何处放置该驱动程序.

I'm new to Java. I'm not sure if I need to download the driver in addition to referencing it in the build.gradle dependency list, and if so, where to place it.

这是我的src/main/java/App.java:

Here's my src/main/java/App.java:

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;

public class App{
        public static void main (String[] args){
                System.out.println("Connecting ... ");
                try {
                        MongoClient client = new MongoClient();
                }
                catch(Exception e) {
                        System.out.println("Failed to connect to MongoDB");
                }

        }
}

推荐答案

最简单的方法是使用Gradle application插件.应用程序插件将自动添加运行任务,该任务将执行指定的主类.将所有运行时依赖项自动放到类路径上:

The easiest thing is to use Gradle application plugin. Application plugin will automatically add run task that will execute the specified main class with all the runtime dependencies automatically put on the classpath:

apply plugin: 'application'

mainClassName = 'App'

dependencies {
    compile 'org.mongodb:mongodb-driver:3.3.0'
}

repositories {
    mavenCentral()
}

您可以通过以下方式运行该应用程序: gradle run

You can run the application by: gradle run

这篇关于Gradle Java和MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆