Search code examples
startupejb-3.1postconstruct

When writing a startupbean (@Singleton @Startup @PostConstruct) is there anyway for me to get the ServletContext?


So I am trying to create a task that fires off at regular intervals and I want it to get some things from the ServletContext:

...
@Singleton
@Startup
public class InitTimers {
    @Resource
    private TimerService timerService;

    @PostConstruct
    public void initTimer() {
        ...
        // I want ServletContext here, how do I?
        ServletContext context = getServletContext();
        ...
    }

    @Timeout
    public void timeout(Timer timer) {
        ...
    }
}

Can an EJB 3.1 @Startup @Singleton access the ServletContext?


Solution

  • No, this is not possible. I recommend moving the logic to a ServletContextListener contextInitialized method, and then call the singleton to do startup work as required.