Create an EJB Startup Service
@Startup
The introduction of singletons also provides a convenient way for EJB
applications to receive callbacks during application initialization or
shutdown. By default, the container decides when to instantiate the
singleton instance. However, you can force the container to
instantiate the singleton instance during application initialization
by using the @Startup annotation. This allows the bean to define a
@PostConstruct method that is guaranteed to be called at startup time.
In addition, any @PreDestroy method for a singleton is guaranteed to
be called when the application is shutting down, regardless of whether
the singleton was instantiated using lazy instantiation or eager
instantiation. In lazy instantiation, the singleton isn't instantiated
until it's method's are first needed. In eager instantiation, the
singleton is instantiated at startup time whether or not it gets used.
@Singleton
@Startup
public class StartupBean {
@PostConstruct
private void startup() { ... }
@PreDestroy
private void shutdown() { ... }
...
}
If you are in a clustered environment this probably will not work for
you out of the box. This only works within a single VM. You will have
your StartupBean called on every server instance starting up or
shutting down. If you have special cluster requirements (e.g. only
initialize once for the complete cluster) you have to think about
synchronizing your StartupBeans by using a database. Usable on any EJB
3.1 compliant container and highly portable. This even should work with the lightweight Java EE 6 Webprofile
https://blogs.oracle.com/enterprisetechtips/entry/a_sampling_of_ejb_3