I have following code:
import javax.inject.Inject;
import models.Subject;
import models.dao.SchoolDao;
import models.dao.SubjectDao;
import play.Application;
import play.GlobalSettings;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class Global extends GlobalSettings{
private Injector injector;
@Inject
private SubjectDao subjectDao;
@Override
public void onStart(Application application) {
injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(SchoolDao.class);
bind(SubjectDao.class);
}
});
insertInitialData();
}
@Override
public <A> A getControllerInstance(Class<A> aClass) throws Exception {
return injector.getInstance(aClass);
}
@Transactional
private void insertInitialData(){
if(subjectDao.countAll() == 0){
Subject deutsch = new Subject();
deutsch.setName("Deutsch");
subjectDao.create(deutsch);
Subject englisch = new Subject();
deutsch.setName("Englisch");
subjectDao.create(englisch);
Subject mathe = new Subject();
deutsch.setName("Mathematik");
subjectDao.create(mathe);
Subject hab = new Subject();
deutsch.setName("Hausaufgabenbetreuung");
subjectDao.create(hab);
}
}
}
As you see I want to seed my database with initial values on startup. I have a data access object "subjectDao" which should be injected. This works on other positions of my application but due to some reason not on applicatin startup. I get a NullPointerException and my subjectDao is null. Has someone an idea.
Looks like you are not actually injecting anything to Global
, you're just binding your classes (and handling controller injection, but that's irrelevant).
You should do that by calling eg. Injector.injectMembers(this)
to get the subjectDao
of your Global
properly injected.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments