22

EJBs seem to be loaded lazily - whenever accessed.

However, I want to initialize them eagerly - i.e. whenever the container starts-up. How is this achieved (in JBoss in particular)

This topic gives some hints, but isn't quite satisfactory.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140

2 Answers2

23

As of EJB 3.1, singleton beans can be notified of module start and stop:

@Singleton
@Startup
public class StartupBean {
    @PostConstruct
    private void postConstruct() { /* ... */ }

    @PreDestroy
    private void preDestroy() { /* ... */ }
}

Prior to EJB 3.1, there is no standard, EJB-only solution. I'd suggest adding a WAR to your EAR and using a servlet-context-listener.

Brett Kail
  • 33,593
  • 2
  • 85
  • 90
  • I found that my app in GlassFish 3.1, the @Singleton @Startup EJB got a @PersistenceContext EntityManager that is closed. My workaround was to have a timer in that EJB that executes 2 seconds later. (duh!) – Hendy Irawan Apr 21 '11 at 21:19
  • 3
    That sounds like a bug to me; I would recommend reporting it. – Brett Kail Apr 21 '11 at 23:16
18

According to Adam Bien's Real World Java EE Patterns - Rethinking Best Practices (see a summary of the patterns) and the Service Starter pattern, it is indeed as bkail suggests

  • with Java EE 6 = EJB 3.1 use @Singleton with @Startup (and perhaps also with @DependsOn)
  • prior to that the only standard and portable way is to use the Servlet API, e.g. a HttpServlet starting the EJBs in its init() method and load-on-startup set to 1 in web.xml.
Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Jakub Holý
  • 6,019
  • 3
  • 33
  • 33