I am in the beginning stages of designing a solution, which I will be building as an application in an application server. Essentially it's a utility service of sorts that can be used by other applications.
Even after about 2 years of J2EE development I'm really a newbie to some aspects of using applications servers.
I think my question should be simple to answer but my googling has turned up nothing.
Where would I put code (or how do I trigger code) that I want to have run 1 when my application starts up, but only after all the other frameworks and services that the J2EE applciation server manages have been initialized.
So that this code can take advantage of all the JNDI, datasources, EJBs and everything else. but it needs to be triggered by the application server not a user and again it only runs once at (the end of) the start-up.
I would of thought that an answer to such a quesiton would be easy to find but it isn't.
Like Peter says, a @Singleton bean annotated with @Startup looks relevant in this case. You can have the datasources and other EJBs injected in that singleton startup bean and that way those services will be available when the bean gets invoked on startup. Something like:
Note, the @Startup annotation will only work on JBoss 6 and above. And if you wish to call EJBs via JNDI which are not located on the same JBoss instance, you will have to use standard lookup code rather than the @EJB annotation.
posted 7 years ago
Thank you everyone for your answers. To re-cap (just to make sure I've got why this will work.)
The @Singleton annotation will convey to the AS that only one instance of this Bean should ever exist.
The @Startup will convey to the AS it should be instantiated as soon as possible upon start-up of the application.
The AS will ensure that all variables annotated with @EJB and @Resource have been injected (or are at least available) prior to this Beans instantiation
The @PostConstruct will automatically get run after this singleton Bean is instantiated and all necessary resources are injected.
Sounds awesome, thanks!
1 Follow-up question out of curiosity, so I know what ASes are an option for this. I know these annotations have been available for a long time. (@EJB, @Resource, @PostConstruct), but what about @Singleton and @Startup do you know which version of the J2EE specification these were introduced in? (or are they JBOSS specific?)
Again, many thanks! I hope this thread helps other's like me as well.
Kevin Embree wrote:but what about @Singleton and @Startup do you know which version of the J2EE specification these were introduced in? (or are they JBOSS specific?)
Java EE6 introduced them and they are portable. Any Java EE6 server will support those. JBoss AS6.x was the first JBoss AS server version to have Java EE6 support, but I would recommend the latest JBoss AS7 version(s).