1

我在实施 neo4j Graphaware 解决方案时遇到问题。以前我正在创建 GraphDatabaseService 对象,如下所示 -

public class TimetreeUtil {
    public static GraphDatabaseService db;
    public static SingleTimeTree st;
    public static TimeTreeBackedEvents ttbe;
    public static TimeTreeBusinessLogic ttbl;
    public static TimedEventsBusinessLogic tebl;    
    public static List<Event> eventsFetchedFromTimetree;

    public TimetreeUtil() {
        db =  new GraphDatabaseFactory( ).newEmbeddedDatabase(new File("..."));
        st = new SingleTimeTree(db);
        ttbl = new TimeTreeBusinessLogic(db);
        ttbe = new TimeTreeBackedEvents(st);
        tebl = new TimedEventsBusinessLogic(db, ttbe);
    }
}

这工作正常。如您所见,GraphDatabaseService、SingleTimeTree、TimeTreeBackedEvents、TimeTreeBusinessLogic 和 TimedEventsBusinessLogic - 都是静态的,它们应该是静态的,因为 neo4j 要求这样做。

但现在我们的架构发生了变化,我们通过以下方式注入 GraphDatabaseService -

@Context
public GraphDatabaseService db;

所以现在班级看起来像 -

public class TimetreeUtil {
        @Context
        public GraphDatabaseService db;
        public static SingleTimeTree st;
        public static TimeTreeBackedEvents ttbe;
        public static TimeTreeBusinessLogic ttbl;
        public static TimedEventsBusinessLogic tebl;    
        public static List<Event> eventsFetchedFromTimetree;

        public TimetreeUtil() {
            st = new SingleTimeTree(db);
            ttbl = new TimeTreeBusinessLogic(db);
            ttbe = new TimeTreeBackedEvents(st);
            tebl = new TimedEventsBusinessLogic(db, ttbe);
        }
    }

辅助类 Timetree 只是通过TimetreeUtil util = new TimetreeUtil();调用 TimetreeUtil 的一个方法来创建 TimetreeUtil 类的对象。

我假设在调用构造函数时,db已经初始化,但事实并非如此。db为空,因此st = new SingleTimeTree(db);给出 NPE。

我怎样才能满足双方的需求?谢谢。

4

1 回答 1

1

依赖注入在对象创建之后运行——Java 必须在设置对象实例变量之前创建对象——因此是 NPE。

也许可以在构造函数中传递对象(值得测试,但我不确定它是否会起作用):

    private GraphDatabaseService db;
    public static SingleTimeTree st;
    public static TimeTreeBackedEvents ttbe;
    public static TimeTreeBusinessLogic ttbl;
    public static TimedEventsBusinessLogic tebl;    
    public static List<Event> eventsFetchedFromTimetree;

    public TimetreeUtil(@Context GraphDatabaseService db) {
        this.db = db
        st = new SingleTimeTree(db);
        ttbl = new TimeTreeBusinessLogic(db);
        ttbe = new TimeTreeBackedEvents(st);
        tebl = new TimedEventsBusinessLogic(db, ttbe);
    }
于 2016-09-24T20:47:44.923 回答