从@Context注入变量初始化其他变量

时间:2016-09-24 07:40:44

标签: java-ee neo4j spring-data-neo4j graphaware

我在实现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。

我怎样才能满足两个目的?感谢。

1 个答案:

答案 0 :(得分: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);
    }