0

我正在创建一个小应用程序来了解 Neo4j 和 Spring Data Neo4j。但我总是得到 NullPointerException 。因此,我使用了 Spring Data Neo4j 最简单的示例之一,并使用 JUnit 中的 main() 更新了测试文件。我的测试文件如下:

package com.spring.nosql.neo4j.worldTest;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.graph.neo4j.template.Neo4jTemplate;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author srahul07
 * 
 */
@ContextConfiguration(locations = "classpath:neo4jBeans.xml")
@Transactional
public class Main {

    @Autowired
    private GalaxyService galaxyService;

    @Autowired
    private Neo4jTemplate template;

    @Rollback(false)
    @BeforeTransaction
    public void shouldAllowDirectWorldCreation() {
        // assertEquals(0, galaxyService.getNumberOfWorlds());
        System.out.println("Number of Worlds: "
                + galaxyService.getNumberOfWorlds());
        World myWorld = galaxyService.createWorld("mine", 0);
        System.out.println("Number of Worlds: "
                + galaxyService.getNumberOfWorlds());
        // assertEquals(1, galaxyService.getNumberOfWorlds());

        Iterable<World> foundWorlds = galaxyService.getAllWorlds();
        World mine = foundWorlds.iterator().next();
        System.out.println("Number of Worlds: " + myWorld.getName() + " Name: "
                + mine.getName());
        // assertEquals(myWorld.getName(), mine.getName());
    }

    public void shouldHaveCorrectNumberOfWorlds() {
        galaxyService.makeSomeWorlds();
        System.out.println("Number of Worlds: "
                + galaxyService.getNumberOfWorlds());
        // assertEquals(13, galaxyService.getNumberOfWorlds());
    }

    public void shouldFindWorldsById() {
        galaxyService.makeSomeWorlds();

        for (World world : galaxyService.getAllWorlds()) {
            World foundWorld = galaxyService.findWorldById(world.getId());
            System.out.println("Found World: " + foundWorld);
            // assertNotNull(foundWorld);
        }
    }

    public void shouldFindWorldsByName() {
        galaxyService.makeSomeWorlds();

        for (World world : galaxyService.getAllWorlds()) {
            World foundWorld = galaxyService.findWorldByName(world.getName());
            System.out.println("Found Worlds: " + foundWorld);
            // assertNotNull(foundWorld);
        }
    }

    public void shouldReachMarsFromEarth() {
        galaxyService.makeSomeWorlds();

        World earth = galaxyService.findWorldByName("Earth");
        World mars = galaxyService.findWorldByName("Mars");

        System.out.println("Mars Rechable from Earth: "
                + mars.canBeReachedFrom(earth));
        System.out.println("Earth Reachable from Mars: "
                + earth.canBeReachedFrom(mars));
        // assertTrue(mars.canBeReachedFrom(earth));
        // assertTrue(earth.canBeReachedFrom(mars));
    }

    public void shouldFindAllWorlds() {
        Collection<World> madeWorlds = galaxyService.makeSomeWorlds();
        Iterable<World> foundWorlds = galaxyService.getAllWorlds();

        int countOfFoundWorlds = 0;
        for (World foundWorld : foundWorlds) {
            System.out.println("Worlds Contains: "
                    + madeWorlds.contains(foundWorld));
            // assertTrue(madeWorlds.contains(foundWorld));
            countOfFoundWorlds++;
        }

        System.out.println("World's Size: " + madeWorlds.size()
                + " Count of Found Worlds: " + countOfFoundWorlds);
        // assertEquals(madeWorlds.size(), countOfFoundWorlds);
    }

    @SuppressWarnings("unchecked")
    public void shouldFindWorldsWith1Moon() {
        galaxyService.makeSomeWorlds();

        for (World worldWithOneMoon : galaxyService.findAllByNumberOfMoons(1)) {

            System.out.println("World With One Moon: "
                    + worldWithOneMoon.getName());
            System.out.println("World With One Moon is Earth?: "
                    + worldWithOneMoon.getName().contains("Earth"));
            System.out.println("World With One Moon is Earth?: "
                    + worldWithOneMoon.getName().contains("Midgard"));

            /*
             * assertThat( worldWithOneMoon.getName(),
             * is(anyOf(containsString("Earth"), containsString("Midgard"))));
             */
        }
    }

    public void shouldNotFindKrypton() {
        galaxyService.makeSomeWorlds();
        World krypton = galaxyService.findWorldByName("Krypton");
        System.out.println("World is Krypton: " + krypton.getName().isEmpty());
        // assertNull(krypton);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        try {
            Main mainTest = new Main();

            mainTest.shouldHaveCorrectNumberOfWorlds();

            mainTest.shouldAllowDirectWorldCreation();

            mainTest.shouldFindAllWorlds();

            mainTest.shouldFindWorldsById();

            mainTest.shouldFindWorldsByName();

            mainTest.shouldFindWorldsWith1Moon();

            mainTest.shouldNotFindKrypton();

            mainTest.shouldReachMarsFromEarth();

        } catch (Exception ae) {
            ae.printStackTrace();
        }

    }

}

我的 Spring 上下文配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/data/neo4j
        http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">


    <context:spring-configured/>
    <context:annotation-config/>
    <context:component-scan base-package="com.spring.nosql.neo4j.worldTest" />

    <neo4j:config storeDirectory="target/neo4j-db"/>
    <neo4j:repositories base-package="com.spring.nosql.neo4j.worldTest"/>
</beans>

每当我运行测试代码时,都会收到以下错误:

java.lang.NullPointerException
    at com.spring.nosql.neo4j.worldTest.Main.shouldHaveCorrectNumberOfWorlds(Main.java:48)
    at com.spring.nosql.neo4j.worldTest.Main.main(Main.java:141)

我的配置中有什么遗漏吗?或者这里有什么额外需要的吗?据我了解,Neo4j 将在“target/neo4j-db”中创建图形数据库。另外,由于我的机器是 Ubuntu,我已经在我的机器上安装了 Neo4j 的 debian 包。所以我也尝试通过使用 REST API 来使用它。因此,为此我对我的 spring 上下文文件进行了以下配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/data/neo4j
        http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">


    <context:spring-configured/>
    <context:annotation-config/>
    <context:component-scan base-package="com.spring.nosql.neo4j.worldTest" />
<neo4j:repositories base-package="com.spring.nosql.neo4j.worldTest"/>

    <neo4j:config graphDatabaseService="graphDatabaseService"/> 
    <bean id="graphDatabaseService" 
      class="org.springframework.data.neo4j.rest.SpringRestGraphDatabase">
      <constructor-arg index="0" value="http://localhost:7474/db/data" />
      <constructor-arg index="1" value="" />
      <constructor-arg index="2" value="" />
     </bean>

但我仍然得到同样的例外。

仅供参考:我在 Eclipse 的构建路径中包含了 Spring、Spring Data Neo4j 和 Neo4j 库。

编辑:

好吧,由于对此没有回应,我尝试了与 JUnit 测试用例相同的示例,如此处示例中提供

在我的 JUnit 测试用例中,每种方法都有以下错误:

java.lang.NoClassDefFoundError: org/neo4j/cypherdsl/grammar/Execute
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2442)
    at java.lang.Class.getDeclaredMethods(Class.java:1808)
    at org.springframework.util.ReflectionUtils.findMethod(ReflectionUtils.java:154)
    at org.springframework.util.ClassUtils.getMostSpecificMethod(ClassUtils.java:730)
    at org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor$AbstractFallbackTransactionAttributeSource.computeTransactionAttribute(TransactionalRepositoryProxyPostProcessor.java:326)
    at org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor$AbstractFallbackTransactionAttributeSource.getTransactionAttribute(TransactionalRepositoryProxyPostProcessor.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy31.count(Unknown Source)
    at com.spring.nosql.neo4j.worldTest.GalaxyService.getNumberOfWorlds(GalaxyService.java:16)
    at com.spring.nosql.neo4j.worldTest.GalaxyServiceTest.shouldAllowDirectWorldCreation(GalaxyServiceTest.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassNotFoundException: org.neo4j.cypherdsl.grammar.Execute
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 43 more

这表示未找到或丢失名为:org/neo4j/cypherdsl/grammar/Execute 的类。

这确实意味着我缺少其中一个库,但 Neo4j 库显示了名为neo4j-cypher-1.8.jar. 但在这我还没有找到cypherdsl

编辑2:

好吧,最后它与 JUnit 一起工作,但不适用于public static void main() [psvm]. 我错过了一个cypherdsl可以从这里下载的库。但是为什么我去的时候它不起作用psvm

4

0 回答 0