问题
I am trying to define a startup class for my application in Weld CDI with @Singleton and @Startup annotations (running on tomcat 7), but my PostConstruct method is never called.
Here is my Startup class:
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.Startup;
import javax.inject.Inject;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import se.raindance.squid.core.domain.SquidSettings;
@Singleton
@Startup
public class InitSquid {
@Inject
private Logger log;
@Inject
EntityManager entityManager;
@PostConstruct
public void init() {
System.out.println("startup!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! InitSquid");
// Init Rainlets
InitRainlets initRainlets = new InitRainlets(entityManager);
initRainlets.init();
initSquidSettings();
}
private void initSquidSettings() {
List<SquidSettings> settingsList = (List<SquidSettings>) entityManager
.createQuery(
"select squidsettings from SquidSettings squidsettings")
.getResultList();
if (settingsList.size() == 0) {
log.info("No SquidSettings entity exists in system, creating one");
SquidSettings settings = new SquidSettings();
settings.setSubledgerRestResourceURI("http://localhost:8080/subledger-webapp/resteasy/");
entityManager.persist(settings);
}
}
}
I tried the hints which I found in these two posts Startup POJO with WELD and Startup EJB doesn't work but neither helped
回答1:
You can not use the @Startup or @javax.ejb.Singleton annotations on a CDI bean: those annotations are meant for EJB's. And EJB's won't work on (plain) Tomcat. If you want to run an EE application on Tomcat, take a look at the TomEE project.
However, there's an AfterDeploymentValidation event that's thrown after everything has been deployed. You can write an observer method to act on that event, as shown in this blog post here:
- Eager CDI beans
来源:https://stackoverflow.com/questions/16413997/startup-class-in-weld