Youcef Laidani Youcef Laidani - 21 days ago 5
Java Question

Use EJB inside Singleton Startup to get information from database

I use

JPA
and i want to get some information from my database, to use them in the startup of my application i use this piece of code:

@Singleton
@Startup
public class StartWhenDeploy {

@EJB
private MyFacade myFacade;

private int info1 = myFacade.getInfo1();
private Date info2 = myFacade.getInfo2();

//...


My facade

@Singleton
@Startup
public class StartWhenDeploy {

@EJB
private AdminUtilisateurFacade adminUtilisateurFacade;

private int PERIOD = adminUtilisateurFacade.getPeriode();
private Date StartDate = adminUtilisateurFacade.getStartDate();
//....


Stack

....
com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NullPointerException
at dz.elit.tresor.commun.util.StartWhenDeploy.<init>(StartWhenDeploy.java:30)
at dz.elit.tresor.commun.util.__EJB31_Generated__StartWhenDeploy__Intf____Bean__.<init>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
...


But this does not work with me, i know why it does not work, because the facades and entities are not yet instantiated, but i look for a solution to this problem.

So is there any other idea how i should get my information from
database
to use them in
Singleton Startup
, or this is not possible?

Thank you.

Answer

I suggest you add a a method annotated @PostContruct, for exemple call it initDataBase, this way it will called after the initialisation of the class :

@PostConstruct
public void initDataBase() {
       .....
}

inside of this method you can call any facade, for exemple :

myFacade.getInfo1();